Created
October 29, 2015 19:31
-
-
Save curtiszimmerman/8ad57741480676e7b016 to your computer and use it in GitHub Desktop.
Nested JSON objects in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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