恐慌:json:如何在 Golang 中解组嵌套的 json 数组

panic: json: How to unmarshall nested json array in Golang

我在解组嵌套的 json 数组时遇到问题。示例如下:

{
  "Subnets": [
    {
      "AvailabilityZone": "xx",
      "AvailabilityZoneId": "xx",
      "AvailableIpAddressCount": 173,
      "CidrBlock": "xx",
      "DefaultForAz": "xx",
      "MapPublicIpOnLaunch": "xx",
      "MapCustomerOwnedIpOnLaunch": "xx",
      "State": "xx",
      "SubnetId": "xx",
      "VpcId": "xx",
      "OwnerId": "xx",
      "AssignIpv6AddressOnCreation": "xx",
      "Ipv6CidrBlockAssociationSet": [],
      "Tags": [
        {
          "Key": "Name",
          "Value": "xx"
        },
        {
          "Key": "workload",
          "Value": "xx"
        },
        {
          "Key": "xx",
          "Value": "xx"
        },
        {
          "Key": "aws:cloudformation:stack-name",
          "Value": "xx"
        },
        {
          "Key": "host_support_group",
          "Value": "xx"
        },
        {
          "Key": "environment",
          "Value": "xx"
        },
        {
          "Key": "client",
          "Value": "xx"
        },
        {
          "Key": "aws:cloudformation:stack-id",
          "Value": "xx"
        },
        {
          "Key": "application",
          "Value": "Subnet"
        },
        {
          "Key": "xx",
          "Value": "xx"
        },
        {
          "Key": "xx",
          "Value": "xx"
        },
        {
          "Key": "xx",
          "Value": "xx"
        },
        {
          "Key": "regions",
          "Value": "ca-central-1"
        }
      ],
      "SubnetArn": "xx"
    }]
  ,
  "ResponseMetadata": {
    "RequestId": "xx",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "xx",
      "cache-control": "no-cache, no-store",
      "strict-transport-security": "max-age=31536000; includeSubDomains",
      "content-type": "text/xml;charset=UTF-8",
      "content-length": "3176",
      "vary": "accept-encoding",
      "date": "xx",
      "server": "AmazonEC2"
    },
    "RetryAttempts": 0
  }
}

我想要的唯一值是 "AvailableIpAddressCount",我尝试使用 interface{} 但我无法获得必要的值。这是 Golang 游乐场 link - playground

错误- I'm getting this error using interface{}

是否有任何其他方法可以仅从 json 对象中提取“AvailableIpAddressCount”值?

感谢任何帮助或参考。

您可以创建一个包含所需字段的结构,并使用该结构解组 JSON 字节,这将填充您的结构中提到的字段。

type Something struct {
    AvailableIpAddressCount int `json:"AvailableIpAddressCount"`
}

var data Something
if err := json.unmarshal(byt, &data); err != nil {
        panic(err)
}

AvailableIpAddressCount = data.AvailableIpAddressCount

Go 使用静态结构来解码 json,因此您可能需要创建一个至少包含您要查找的内容的结构。如果您有自己的结构,则可以像这样访问 AvailableIPAddressCount

tmp.Subnets[0].AvailableIPAddressCount

这里是游乐场https://play.golang.org/p/FsjeOubov1Q

要从示例 json 创建 json 结构,您可以使用 this.

等工具

如果需要遍历所有子网:

for _, subnet := range tmp.Subnets {
    fmt.Println(subnet.AvailableIPAddressCount)
}

如果您想动态地使用 json,您也可以使用 https://github.com/spf13/viper。但它可能比静态解码慢。