Parsing arbitrary JSON documents

suggest change

Parsing into a struct is very convenient but sometimes you don’t know the structure of JSON document upfront.

For an arbitrary JSON object we can decode into a map[string]interface{}. A top-level array or scalar needs a different Go type.

var jsonStr = `{
	"name": "Jane",
	"age": 24,
	"city": "ny"
}`

	var doc map[string]interface{}
	err := json.Unmarshal([]byte(jsonStr), &doc)
	if err != nil {
		log.Fatalf("json.Unmarshal failed with '%s'\n", err)
	}
	fmt.Printf("doc: %#v\n", doc)
	name, ok := doc["name"].(string)
	if !ok {
		log.Fatalf("doc has no key 'name' or its value is not string\n")
	}
	fmt.Printf("name: %#v\n", name)
doc: map[string]interface {}{"age":24, "city":"ny", "name":"Jane"}
name: "Jane"

For basic JSON types, the value in the map is bool, float64, or string. A JSON number is a float64 here, even when it looks like an integer. json.Decoder.UseNumber keeps the number as a json.Number string instead.

For JSON arrays, the value is []interface{}.

For JSON objects, the value is again map[string]interface{}.

This approach is flexible but dealing with map[string]interface{} to access values is rather painful.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents