panic: json: 如何在戈朗中取消马歇尔嵌套 json 数组

我在取消编组嵌套的 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

  }

}

繁花不似锦
浏览 106回答 2
2回答

炎炎设计

您可以使用所需字段创建一个结构,并使用该结构取消封送 JSON 字节,该结构将填充结构中提到的字段。type Something struct {    AvailableIpAddressCount int `json:"AvailableIpAddressCount"`}var data Somethingif err := json.unmarshal(byt, &data); err != nil {        panic(err)}AvailableIpAddressCount = data.AvailableIpAddressCount

慕莱坞森

Go 使用静态结构来解码 json,因此您可能需要创建一个至少包含您要查找的内容的结构。如果您有您的结构,则可以像这样访问可用IP地址计数:tmp.Subnets[0].AvailableIPAddressCount这是游乐场 https://play.golang.org/p/FsjeOubov1Q。要从示例 json 创建 json 结构,可以使用此类工具。如果需要遍历所有子网:for _, subnet := range tmp.Subnets {     fmt.Println(subnet.AvailableIPAddressCount) }如果要动态使用 json,也可以使用 https://github.com/spf13/viper。但它可能比静态解码慢。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go