-
-
Save benjiqq/97d904ff0fd5fab96d666db973be9e3d to your computer and use it in GitHub Desktop.
Example of generic Golang json parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"reflect" | |
"fmt" | |
) | |
type GenericObj struct { | |
Overwrite interface{} `json:"overwrite"` | |
} | |
func main() { | |
var jsonBlob = []byte(`{ | |
"overwrite": [{"value":{"first":true,"second":5}},{"someotherobj":"a string"}] | |
}`) | |
var body GenericObj | |
//fmt.Println("%+v", body) | |
err := json.Unmarshal(jsonBlob, &body) | |
if err != nil { | |
fmt.Println("error:", err) | |
} | |
//fmt.Println("%+v", body) | |
bodyContents, _ := body.Overwrite.([]interface{}) | |
//fmt.Println(reflect.ValueOf(bodyContents).Kind()) | |
//fmt.Println(bodyContents) | |
for k, v := range bodyContents { | |
fmt.Println("key ", k) | |
fmt.Println("value ", v) | |
if reflect.ValueOf(v).Kind() == reflect.Map { | |
printMap(v) | |
} | |
} | |
} | |
func printMap(m interface{}) { | |
vm := reflect.ValueOf(m) | |
if vm.Kind() != reflect.Map { | |
fmt.Println("not a map") | |
return | |
} | |
for k, v := range m.(map[string]interface{}) { | |
fmt.Println("key ", k) | |
fmt.Println("value ", v) | |
if reflect.ValueOf(v).Kind() == reflect.Map { | |
printMap(v) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment