Decoding with interfaces, maps, and slices
When decoding Go values to JSON, the Go value types dictate how JSON encoding will be done. JSON does not have a rich type system like Go. Valid JSON types are string, number, boolean, object, array, and null. When you decode JSON data into a Go struct, it is still the Go type system that dictates how JSON data should be interpreted. But when you decode JSON into an interface{}
, things change. Now it is the JSON data that dictates how Go values should be constructed, and this sometimes causes unexpected results.
How to do it...
To unmarshal JSON data into an interface, use the following:
var output interface{} err:=json.Unmarshal(jsonData,&output)
This creates an object tree based on the following translation rules:
JSON |
Go |
Object |
|
Array... |