Search code examples
arraysjsongounmarshalling

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


I'm having trouble unmarshalling a nested json array. Sample below:

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

The only value I want is "AvailableIpAddressCount", I tried using interface{} but I'm not able to get the necessary value. Here's the Golang playground link - playground

Error- I'm getting this error using interface{}

Is there any other way to extract just the "AvailableIpAddressCount" value from the json object?

Any help or references are appreciated.


Solution

  • You can create a struct with the desired field and unmarshal the JSON bytes using that struct which will populate fields mentioned in your struct.

    type Something struct {
        AvailableIpAddressCount int `json:"AvailableIpAddressCount"`
    }
    
    var data Something
    if err := json.unmarshal(byt, &data); err != nil {
            panic(err)
    }
    
    AvailableIpAddressCount = data.AvailableIpAddressCount