Golang : Decode/unmarshal unknown JSON data type with map[string]interface
This tutorial is courtesy of Rohan Allison on how to decode or unmarshal JSON into map[string]interface. There are times we only know in advance that the top-level keys are in string type and not the data type.
So how to handle the data type? Golang doesn't support generic yet. Aha! interface can handle the unknown data type.
Here you go!
package main
import "fmt"
import "encoding/json"
func main() {
// Given a possibly complex JSON object
msg := "{\"assets\" : {\"old\" : 123}}"
// We only know our top-level keys are strings
mp := make(map[string]interface{})
// Decode JSON into our map
err := json.Unmarshal([]byte(msg), &mp)
if err != nil {
println(err)
return
}
// See what the map has now
fmt.Printf("mp is now: %+v\n", mp)
// Iterate the map and print out the elements one by one
// Note: that mp has to be deferenced here or range will fail
for key, value := range mp {
fmt.Println("key:", key, "value:", value)
}
}
Output :
mp is now: map[assets:map[old:123]]
key: assets value: map[old:123]
https://play.golang.org/p/-aM7yokAHd
Happy coding! and once again thanks to Mr. Rohan Allison for the code example!
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.3k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+22.6k Golang : Upload to S3 with official aws-sdk-go package
+15.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+4.7k Swift : Get substring with rangeOfString() function example
+6.4k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+5.5k Golang : Combine slices of complex numbers and operation example
+9.3k Generate Random number with math/rand in Go
+18.2k Golang : Measure http.Get() execution time
+7.7k Golang : Accept any number of function arguments with three dots(...)
+15.5k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+32.3k Golang : All update packages with go get command