嵌套 json 将 2d 切片解组为结构在 golang 中不起作用

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

我的json结构看起来像

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

我正在尝试将它添加到一个结构中,该结构看起来像

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"`
}

但是,当我打印结构时,我只从 2D 切片中得到一个值,除此之外什么也没有。

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 ]] [] [] []}}}]}

但是如果我在结构中省略二维切片,例如

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"`
}

一切都打印为

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

有人可以帮我确定这里出了什么问题吗?

Here 是带有结构和示例 json 的 golang 操场的 link。两个 TwoD 切片在结构中有注释。

注意:: 编辑了 playground link,其中一个 2d 切片未注释,以便可以注意到差异,并将类型字符串更改为 bool,如 @cnicutar 所指出的,谢谢。

主要问题是您没有处理 json.Unmarshal 返回的错误。一旦你处理了这个问题,你的 json(和解码结构)的问题就变得很明显了。

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

第一个:

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

所以Add_info应该是bool。修复后取消注释 Applications:

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

将 12 更改为“12”,将 106 更改为“106”后,结果为:

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