Skip to content

Instantly share code, notes, and snippets.

@alexhudici
Last active January 10, 2023 14:56
Show Gist options
  • Save alexhudici/55d51530588fcba75a471638525d1de5 to your computer and use it in GitHub Desktop.
Save alexhudici/55d51530588fcba75a471638525d1de5 to your computer and use it in GitHub Desktop.
Example of generic Golang json parsing
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)
}
}
}
@alexhudici
Copy link
Author

Created in this Go playground https://play.golang.org/p/vHOLTnZXdI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment