Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Created January 19, 2015 20:29
Show Gist options
  • Save ericchiang/00e10abf1c5408950c3c to your computer and use it in GitHub Desktop.
Save ericchiang/00e10abf1c5408950c3c to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"log"
)
var data = `
{"menu": {
"id": "file",
"value": "File",
"tf": null,
"popup": {
"menuitems": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}`
func main() {
// a crazy specific struct with a huge number of levels
// when declared on the fly like this, we call these anonymous structs
s := struct {
Menu struct {
Id string `json:"id"`
Value string `json:"value"`
Popup struct {
MenuItems []struct {
Value string `json:"value"`
OnClick string `json:"onclick"`
} `json:"menuitems"`
} `json:"popup"`
} `json:"menu"`
}{} // this last '{}' initializes the struct so it's an instance rather than a type
// you can turn strings into an array of bites with this trick
dataAsBytes := []byte(data)
// always pass the pointer (the address of the thing) to what you're decoding into
// this is what the '&' is for
err := json.Unmarshal(dataAsBytes, &s)
if err != nil {
log.Fatal(err) // always check your errors
}
fmt.Printf(".menu.id: '%s'\n", s.Menu.Id)
fmt.Printf(".menu.popup.menuitems.[0].value: '%s'\n", s.Menu.Popup.MenuItems[0].Value)
fmt.Printf(".menu.popup.menuitems.[0].onclick: '%s'\n", s.Menu.Popup.MenuItems[0].OnClick)
// we can totally just use the fields now
items := s.Menu.Popup.MenuItems
fmt.Printf(".menu.popup.menuitems: %s\n", items)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment