Created
October 27, 2013 10:49
-
-
Save tomnomnom/7180339 to your computer and use it in GitHub Desktop.
Parsing arbitrary JSON with go
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 ( | |
"log" | |
"fmt" | |
"encoding/json" | |
) | |
func main() { | |
b := []byte(`{"name": "tom", "favNum": 6, "interests": ["knives", "computers"], "usernames": {"github": "TomNomNom", "twitter": "@TomNomNom"}}`) | |
var f interface{} | |
err := json.Unmarshal(b, &f) | |
if err != nil { | |
log.Fatal("Failed to parse JSON") | |
} | |
m := f.(map[string]interface{}) | |
printStruct("", m) | |
} | |
func printStruct(prefix string, m map[string]interface{}) { | |
for k, v := range m { | |
switch vv := v.(type) { | |
case string: | |
fmt.Println(prefix, k, "is string", vv) | |
case float64: | |
fmt.Println(prefix, k, "is number", vv) | |
case []interface{}: | |
fmt.Println(prefix, k, "is an array:") | |
for i, u := range vv { | |
fmt.Println(prefix, i, u) | |
} | |
case map[string]interface{}: | |
fmt.Println(prefix, k, "is a map:") | |
printStruct(prefix + " ", vv) | |
default: | |
fmt.Println(prefix, k, "is a type we can't handle", vv) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment