I have what I would consider a very messy block of JSON, and I want to read and modify two values that are deeply nested within (denoted: I want this!) using Go. Due to the server that I am sending it to, I cannot change the label names. What makes it especially difficult for me is that parents have multiple children which are also nested, and since there are so many "value" labels I don't know how to specify which "value" child thatI want to enter.
I got the values in Bash very quickly using this
jq ' .value[0].value[1].value[0].value[1].value[0].value="'"$one"'" | '\ '
.value[0].value[1].value[0].value[1].value[1].value="'"$two"'"'
I tried a format like this in Go initially, but could not get it working because of the issue where children are all named "value" and I want to go into one other than the first. Unfortunately none of those magic JSON to Go struct were able to handle all of the nesting either.
type Bar struct {
Value struct { // Value[0]
Value struct { // Value[1]
Value struct { // Value[0]
Value struct { // Value[1]
Value struct { // Value[1] or Value[2]
}}}}}}
This code converts the JSON into a more struct/map friendly form, and prints the whole thing.
var foo interface{}
err := json.Unmarshal(blob, &foo)
if err != nil {
fmt.Println("error:", err)
}
m := foo.(map[string]interface{})
// print all
fmt.Println("Loop: ", m)
for k, v := range m {
fmt.Printf("%v : %v", k, v)
}
Here is the JSON that I am storing as a variable
var blob = []byte(`{
"tag": "1",
"value": [{
"tag": "2",
"value": [{
"tag": "3",
"value": [{
"tag": "4",
"type": "x",
"value": "x"
}, {
"tag": "5",
"type": "x",
"value": "x"
}
]
}, {
"tag": "6",
"value": [{
"tag": "7",
"value": [{
"tag": "8",
"type": "x",
"value": "x"
}, {
"tag": "9",
"value": [{
"tag": "10",
"type": "x",
"value": "I want this!"
}, {
"tag": "11",
"type": "Thanks for the help mate!",
"value": "I want this!"
}
]
}
]
}
]
}, {
"tag": "12",
"type": "x",
"value": "x"
}
]
}, {
"tag": "13",
"value": [{
"tag": "14",
"type": "x",
"value": "x"
}, {
"tag": "15",
"value": [{
"tag": "16",
"value": [{
"tag": "17",
"type": "x",
"value": "x"
}
]
}
]
}
]
}
]
}`)
I would appreciate any help or advice that you could give me.