Skip to content

Instantly share code, notes, and snippets.

@benjiqq
Forked from alexhudici/generic_json_parsing.go
Created January 10, 2023 14:56
Show Gist options
  • Save benjiqq/97d904ff0fd5fab96d666db973be9e3d to your computer and use it in GitHub Desktop.
Save benjiqq/97d904ff0fd5fab96d666db973be9e3d 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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment