Sometimes, parsing a json structure from a source which can give unpredictable types can become a mess. A good example for parsing the types of unmarshalling json:
package main
import (
"encoding/json"
"fmt"
)
func main() {
// consider that we have parsed huge json file 60MB plus size
b := []byte(`{"section1" : {"data" : [{"F1" : "F1 data","F2" : "F2 data"},{"F1" : "demo 123","F2" : "abc xyz"}],"details" : {"F1" : "Field 1","F2" : "Field 2"}},"section2" : {"data" : [{"F1" : "f1 dummy data","F2" : "test"},{"F1" : "1234abc","F2" : "123d"}],"labels" : {"F1" : "Field 1","F2" : "Field 2"}}}`)
var f interface{}
_ = json.Unmarshal(b, &f)
parsedMap := f.(map[string]interface{})
ProcessMap(parsedMap)
}
// how to concurently call while making recurrsion. fmt can be ignored in that case
func ProcessMap(m map[string]interface{}) {
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
case map[string]interface{}:
fmt.Println(k, "is an map:")
//Will have some check to determine if the sub map is really huge
//If huge then process it concurrently
ProcessMap(vv)
default:
fmt.Println(k, "is of a type I don't know how to handle ")
}
}
}
Play Blokr Now FREE!
blokr.io the web game where you can eat other blocks!