How To Handle Key/Value Pairs in JSON

Hello,

I am working on parsing an API that appears to only return data in a format such as:

[  
    {  
       'key':'TU_STATUS_PRIMARY_VOLT',
       'value':'4.1000000000000005'
    },
    {  
       'key':'TU_STATUS_PRIMARY_CHARGE_PERCENT',
       'value':'90'
    },
    {  
       'key':'DOOR_IS_ALL_DOORS_LOCKED',
       'value':'FALSE'
    }
…
]

I cannot seem to figure out the best approach to parsing this API. JSONPath doesn’t seem to do what I need, unless I am misunderstanding the documentation. Could anyone suggest an approach?

What makes you think JSONPATH won’t work on this?

Assuming your json string is in a variable named s

Something like this will tell you how many elements are in the JSON array.

    val int numElements = Integer.parseInt(transform("JSONPATH", "$.length()", s))
    logInfo("test", "There are {} elements in array", numElements)

Then you can iterate over the array elements like this.

    var int i
    var String key
    var String value
    for (i=0; i < numElements; i++) {
        key = transform("JSONPATH", "$.[" + i + "].key", s)
        value = transform("JSONPATH", "$.[" + i + "].value", s)
        logInfo("test", "key:value={}:{}", key, value)
    }
2 Likes

Thank you, this is super helpful. I will give this a go tonight/tomorrow.