Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active August 29, 2015 14:10
Show Gist options
  • Save montanaflynn/2185170642e95f32ca96 to your computer and use it in GitHub Desktop.
Save montanaflynn/2185170642e95f32ca96 to your computer and use it in GitHub Desktop.
Decoding JSON in Golang
package main
import (
"fmt"
"encoding/json"
)
type User struct {
User UserData `json:"User"`
}
type UserData struct {
Name string `json:"name"`
Organization Organization `json:"organization"`
}
type Organization struct {
Name string `json:"name"`
Details []interface{} `json:"details"`
}
func main() {
// Pretend JSON data
data := `{"User":{"name":"montanaflynn","organization":{"name":"Mashape","details":[{"a":"b"},2,3]}}}`
// Using structs
fmt.Println("JSON to go structs:")
u := User{}
json.Unmarshal([]byte(data), &u)
fmt.Printf("%+v", u)
fmt.Println("\n\n")
// Using generic interface
fmt.Println("JSON to go interface:")
var y interface{}
json.Unmarshal([]byte(data), &y)
fmt.Printf("%+v", y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment