Last active
August 29, 2015 14:10
-
-
Save montanaflynn/2185170642e95f32ca96 to your computer and use it in GitHub Desktop.
Decoding JSON in Golang
This file contains hidden or 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
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