Given this JSON
{
"users": [
{
"name" : "Elliot",
"type" : "Reader",
"age" : 23,
"social" : {
"facebook" : "https://facebook.com",
"twitter" : "https://twitter.com"
}
},
{
"name" : "Fraser",
"type" : "Author",
"age" : 17,
"social" : {
"facebook" : "https://facebook.com",
"twitter" : "https://twitter.com"
}
}
]
}
I need a function/library to return a map in order to do myMap[0].name
to get the value "Elliot". Is there anyone who can help me? Thanks.
I wish to access to that field in much beautiful notation associative-array like Res["users"][0].Name, or something like that.
As mentioned in comments, arguably the nicest way would be using structs
type User struct {
Name string `json:"name"`
Type string `json:"type"`
Age int `json:"age"`
Social struct {
Facebook string `json:"facebook"`
Twitter string `json:"twitter"`
} `json:"social"`
}
type Config struct {
Users []User `json:"users"`
}
rawJSON := []byte(`{...your config JSON in here...}`)
config := Config{}
if err := json.Unmarshal(rawJSON, &config); err != nil {
log.Fatal(err)
}
user := config.Users[0]
fmt.Printf(
"name: %s, type: %s, age: %d, facebook: %s, twitter: %s
",
user.Name,
user.Type,
user.Age,
user.Social.Facebook,
user.Social.Twitter,
)
Result:
name: Elliot, type: Reader, age: 23, facebook: https://facebook.com, twitter: https://twitter.com