Parsing arbitrary JSON documents
suggest changeParsing into a struct is very convenient but sometimes you don’t know the structure of JSON document upfront.
For arbitrary JSON documents we can decode into a map[string]interface{}
, which can represent all valid JSON documents.
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
, int
, float64
or string
.
For JSON arrays, the value is []interface{}
.
For JSON dictionaries, the value is (again) map[string]interface{}
.
This approach is flexible but dealing with map[string]interface{}
to access values is rather painful.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents