首页 > 解决方案 > GO中的嵌套数组

问题描述

我正在尝试将以下 JSON 映射到map[string]interface{}in go:

{
    "Container": {
        "destinationPath": "/path",
        "volumeMountPath": "/data",
        "token": "token",
        "URL": "https://someurl.com",
        "ids": [{
                "id": "2322",
                "version": "878475"
            },
            {
                "id": "66474",
                "version": "6647"
            }
        ]
    }
}

到目前为止,我有:

Data: map[string]interface{}{
    "Container": struct {
        destinationPath string
        volumeMountPath string
        token string
        URL string
        }{"/path", 
          "/data", 
           "someToken",
           "https://someurl.com"},
          },

但我不确定如何表示 id 数组。

编辑:这是我到目前为止所拥有的,ID 已设置,但destinationPath、volumeMountPath 和令牌未设置。

Data: map[string]interface{}{
        "Container": struct {
            destinationPath string
            volumeMountPath string
            token string
            URL string
            }{"/path", 
              "/data", 
               "someToken",
               "https://someurl.com"},
              },

            "ids": []map[string]interface{}{
                 map[string]interface{}{
                 `id`:"3q423442",
                 `version`:"325435355",
                },
            },
        },

谢谢

标签: arraysjsongo

解决方案


这似乎做到了:

package main
import "fmt"

type (
   a []interface{}
   m map[string]interface{}
)

func main() {
   n := m{
      "Container": m{
         "URL": "https://someurl.com",
         "destinationPath": "/path",
         "token": "token",
         "volumeMountPath": "/data",
         "ids": a{
            m{"id": "2322", "version": "878475"},
            m{"id": "66474", "version": "6647"},
         },
      },
   }
   fmt.Println(n)
}

推荐阅读