Mondo
Mondo

Reputation: 163

Parse json nested object

This question is similar to this question and has help from this question however while I think the json parse I am applying should work:

println(json.value[i].properties.instanceData)

result

{
   "Microsoft.Resources" : {
      "location" : "Asiseast",
      "tags" : {
         "costCentre" : "2222",
         "Department" : "DEPT",
         "Project" : "IaaS"
      },
      "resourceUri" : "/subscriptions/xxx-xxx-xxx-xxx/resourceGroups/RGNAME/providers/Microsoft.Compute/virtualMachines/VMNAME",
      "additionalInfo" : {
         "ServiceType" : "",
         "ImageType" : "",
         "VMProperties" : "",
         "UsageType" : "DataTrOut",
         "VMName" : ""
      }
   }
}

I try to pull the value of 'Microsoft-Resources' out of this with the following query -

println(json.value[i].properties.instanceData["Microsoft.Resources"])

but I get the following response:

Caught: groovy.lang.MissingPropertyException: No such property: Microsoft.Resources for class: java.lang.String

Trying -

println(json.value[i].properties.instanceData."Microsoft.Resources")

result:

Caught: groovy.lang.MissingPropertyException: No such property: Microsoft.Resources for class: java.lang.String

For reference, the output to

println(json.value[i].properties)

is

[subscriptionId:xxx-xxx-xxx-xxx-xxx,     
     usageStartTime:2018-01-01T00:00:00+00:00, 
     usageEndTime:2018-01-02T00:00:00+00:00, 
     meterName:Premium Storage - Snapshots (GB), 
     meterRegion:AU East, 
     meterCategory:Storage, 
     meterSubCategory:Locally Redundant, 
     unit:GB, 
     instanceData:
          {
           "Microsoft.Resources":{
               "resourceUri":"/subscriptions/ xxx-xxx-xxx-xxx-xxx /resourceGroups/RGNAME/providers/Microsoft.Storage/storageAccounts/STGNAME",
               "location":"aueast",
               "tags":{
                   "Project":"XXX",
                   "costCentre":"1234"
                 }
            }
       },
     meterId:b74c1bd6-c0ea-4248-b00a-dfe2afce7af0, 
     infoFields:[:], 
     quantity:0.005514

]

Upvotes: 1

Views: 902

Answers (1)

Evgeny Smirnov
Evgeny Smirnov

Reputation: 3016

This happends beacause json.value[i].properties.instanceData is instance of String as described in error message.

You need to parse this string to json.

def parsedJson = new groovy.json.JsonSlurper().parseText(json.value[i].properties.instanceData)
println parsedJson['Microsoft.Resources']

Upvotes: 2

Related Questions