Skip to content

Instantly share code, notes, and snippets.

@curtiszimmerman
Created October 29, 2015 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curtiszimmerman/8ad57741480676e7b016 to your computer and use it in GitHub Desktop.
Save curtiszimmerman/8ad57741480676e7b016 to your computer and use it in GitHub Desktop.
Nested JSON objects in Go
import (
"fmt"
"encoding/json"
)
/*
// example JSON object
{
"foo": 0,
"bar": false,
"x": {
"y": "z",
"a": "b",
"one": {
"two": "three"
}
},
"things": [{
"title": "uno",
"content": "gee whiz"
},{
"title": "dos",
"content": "awesome"
},{
"title": "tres",
"content": "superb"
}]
}
*/
func main() {
example := []byte(`{
"foo": 0,
"bar": false,
"x": {
"y": "z",
"a": "b",
"one": {
"two": "three"
}
},
"things": [{
"title": "uno",
"content": "gee whiz"
},{
"title": "dos",
"content": "awesome"
},{
"title": "tres",
"content": "superb"
}]
}`)
type MetavariableStruct struct {
Foo int `json:"foo"`
Bar bool `json:"bar"`
X struct {
Y string `json:"y"`
A string `json:"a"`
One struct {
Two string `json:"two"`
}
}
Things []struct {
Title string `json:"title"`
Content string `json:"content"`
}
}
var metaVars map[string]interface{}
if err := json.Unmarshal(example, &metaVars); err != nil {
fmt.Println(err)
}
fmt.Println(result["things"].([]interface{})[0].(map[string]interface{})["title"].(string))
metaVarObject := &MetavariableStruct{}
if err := json.Unmarshal(example, &metaVarObject); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", metaVarObject)
fmt.Println(metaVarObject.Things[0].Title)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment