nohup nohup - 6 months ago 76
JSON Question

Nested json unmarshaling with 2d slices into struct not working in golang

I have a json structure that looks like

{
"devices": [
{
"server": {
"bu": {
"add_info": false,
"applications": [
[
"Systems",
12
],
[
"SomeProject",
106
]
],
"name": [
[
"SomeName",
4
],
[
"CommonName",
57
]
],
"owners": [
"SomeOwner1",
"SomeOwner2"
],
"users": [
"SomeUser1",
"SomeUser2"
]
}
}
}
]
}


I am trying to add it to a struct, and the struct looks like

type TwoD [][]string
type MainContainer struct {
Devices []struct{
Server struct{
Bu struct{
Add_info string `json:"add_info"`
Applications TwoD `json:"applications"`
Name TwoD `json:"name"`
Owners []string `json:"owners"`
Users []string `json:"users"`
} `json:"bu"`
} `json:"server"`
} `json:"devices"`
}


However, when I am printing the struct, I get only one value from the 2D slice and nothing beyond it.

func main() {
jsonfile, err := ioutil.ReadFile("./search.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var jsonobject MainContainer
json.Unmarshal(jsonfile, &jsonobject)
fmt.Printf("%v", jsonobject)
}


{[{{{ [[Systems ]] [] [] []}}}]}


But if I am omitting the 2d slices in the struct like

type MainContainer struct {
Devices []struct{
Server struct{
Bu struct{
Add_info string `json:"add_info"`
//Applications TwoD `json:"applications"`
//Name TwoD `json:"name"`
Owners []string `json:"owners"`
Users []string `json:"users"`
} `json:"bu"`
} `json:"server"`
} `json:"devices"`
}


everything is printed as

{[{{{ [SomeOwner1 SomeOwner2] [SomeUser1 SomeUser2]}}}]}


Could someone help me identify what is wrong here?

Here is the link to the golang playground with the struct and sample json. The two TwoD slices are commented in the struct there.

Note:: Edited the playground link with one 2d slice uncommented so that the difference can be noted, and changed the type string to bool, as pointed out by @cnicutar, Thank you.

Answer

The main problem is that you're not handling the error returned by json.Unmarshal. Once you handle that, problems with your json (and the decoding struct) become obvious.

if err := json.Unmarshal(jsonfile, &jsonobject); err != nil {
    fmt.Printf("Unmarshal: %v\n", err)
}

First:

Unmarshal json: cannot unmarshal bool into Go value of type string

So Add_info should be bool. After fixing that and uncommenting Applications:

Unmarshal json: cannot unmarshal number into Go value of type string

After changing 12 to "12" and 106 to "106" the result is:

{[{{{false [[Systems 12] [SomeProject 106]] [SomeUser1 SomeUser2]}}}]}