Skip to content

Instantly share code, notes, and snippets.

@tomnomnom
Created October 27, 2013 10:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomnomnom/7180339 to your computer and use it in GitHub Desktop.
Save tomnomnom/7180339 to your computer and use it in GitHub Desktop.
Parsing arbitrary JSON with go
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