'How to parse json array struct
I'm using the following code without success to parse json value but its inside array []
https://play.golang.org/p/5HdWeyEtvie
package main
import (
"encoding/json"
"fmt"
)
var input = `
[
{
"created_at": "Thu May 31 00:00:01 +0000 2012"
},
{
"created_at": "Thu May 31 00:00:01 +0000 2012"
}
]
`
func main() {
var val map[string]interface{}
if err := json.Unmarshal([]byte(input), &val); err != nil {
panic(err)
}
fmt.Println(val)
}
The idea is to get the value as key and print it , like a function that get string parameter="created_at" and prints it.
Solution 1:[1]
You're unmarshaling an array to a map. That obviously won't work. you need val
to be an array.
func main() {
var val []map[string]interface{} // <---- This must be an array to match input
if err := json.Unmarshal([]byte(input), &val); err != nil {
panic(err)
}
fmt.Println(val)
}
Solution 2:[2]
Your input is:
[
{
"created_at":"Thu May 31 00:00:01 +0000 2012"
},
{
"created_at":"Thu May 31 00:00:01 +0000 2012"
}
]
You can turn this into a struct like so:
type MyArray []struct {
CreatedAt string `json:"created_at"`
}
Now you can read your JSON data and loop through it to get your desired values. Here's what you get:
package main
import (
"encoding/json"
"fmt"
)
var str = `[
{
"created_at": "Thu May 31 00:00:01 +0000 2012"
},
{
"created_at": "Thu May 31 00:00:01 +0000 2013"
}
]`
type MyArray struct {
CreatedAt string `json:"created_at"`
}
func main() {
var m []MyArray
if err := json.Unmarshal([]byte(str), &m); err != nil {
panic(err)
}
for _, val := range m {
fmt.Println(val.CreatedAt)
}
}
In the future, you could consult JSON-to-Go if you're unsure how to convert a JSON object to a struct -- it's quite useful. Cheers!
Solution 3:[3]
You should create a struct like this.
type Data struct {
CreateAt time.Time `json:"create_at"`
}
func main() {
var in []Data
if err := json.Unmarshal([]byte(input), &in); err != nil{
log.Fatal(err)
}
for _, data := range in{
fmt.Println(data.CreateAt)
}
}
Solution 4:[4]
var input = `[
{
"created_at": "Thu May 31 00:00:01 +0000 2012"
},
{
"created_at": "Thu May 31 00:00:01 +0000 2013"
}
]`
func main() {
var val []struct {
CreatedAt string `json:"created_at"`
}
if err := json.Unmarshal([]byte(input), &val); err != nil {
panic(err)
}
fmt.Println(val[0].CreatedAt)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Flimzy |
Solution 2 | solo |
Solution 3 | KibGzr |
Solution 4 | starriet |