I have a http server and I would like to handle JSON responses to overwrite a JSON file, and I want to be able to parse any amount of data and structure.
So my JSON data could look like this:
{
"property1": "value",
"properties": {
"property1": 1,
"property2": "value"
}
}
Or it can look like this:
{"property": "value"}
I would like to iterate through each property, and if it already exists in the JSON file, overwrite it's value, otherwise append it to the JSON file.
I have tried using map
but it doesn't seem to support indexing. I can search for specific properties by using map["property"]
but the idea is that I don't know any of the JSON data yet.
How can I (without knowing the struct) iterate through each property and print both its property name and value?
How can I (without knowing the struct) iterate through each property and print both its property name and value?
Here is a basic function that recurses through the parsed json data structure and prints the keys/values. It's not optimized and probably doesn't address all edge cases (like arrays in arrays), but you get the idea. Playground.
Given an object like {"someNumerical":42.42,"stringsInAnArray":["a","b"]}
the output is something like the following:
object {
key: someNumerical value: 42.42
key: stringsInAnArray value: array [
value: a
value: b
]
value: [a b]
}
Code:
func RecurseJsonMap(dat map[string]interface{}) {
fmt.Println("object {")
for key, value := range dat {
fmt.Print("key: " + key + " ")
// print array properties
arr, ok := value.([]interface{})
if ok {
fmt.Println("value: array [")
for _, arrVal := range arr {
// recurse subobjects in the array
subobj, ok := arrVal.(map[string]interface{})
if ok {
RecurseJsonMap(subobj)
} else {
// print other values
fmt.Printf("value: %+v
", arrVal)
}
}
fmt.Println("]")
}
// recurse subobjects
subobj, ok := value.(map[string]interface{})
if ok {
RecurseJsonMap(subobj)
} else {
// print other values
fmt.Printf("value: %+v
" ,value)
}
}
fmt.Println("}")
}
func main() {
// some random json object in a string
byt := []byte(`{"someNumerical":42.42,"stringsInAnArray":["a","b"]}`)
// we are parsing it in a generic fashion
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
RecurseJsonMap(dat)
}