craig
craig

Reputation: 26272

Get a value associated with a key in an array of JSON objects in a Logic App expression

Given this JSON hash:

{
    "id": 55555,
    "name": "111111",
    "custom_data_field": [
        {
            "id": 1,
            "label": "Vehicle Type",
            "value": "Coach"
        },
        {
            "id": 2,
            "label": "Vendor",
            "value": 1
        }
    ]
}

I need the value associated with each label.

I'm able to get the value using the array's index:

@item()?['custom_data_field'][0]['value'] # Coach
@item()?['custom_data_field'][1]['value'] # 1

But this is a bit fragile.

This syntax doesn't work:

@item()?['custom_data_field'][@label=='Vehicle Type']['value'] # Coach
@item()?['custom_data_field'][@label=='Vendor']['value'] # 1

Is there a way to do this reliably?

Upvotes: 1

Views: 11848

Answers (1)

Hury Shen
Hury Shen

Reputation: 15754

According to the description of your question, it seems the data {"id": 55555, "name": "111111"....} you provided is an item of a array list because your expression begins with item() (I guess you use this expression in a "For each" or something else loop action). And custom_data_field is array under the item, you want to do filter/select operation to get the value which its label equals Vehicle Type just by the expression. I don't think we can do it just in one expression (because the label and value are not key-value map, we can not do the filter/select in expression easily).

To meet the requirement, we need to use a more sophisticated approach such as "Filter array" action mentioned by Scott in comments. We need to set the array custom_data_field to the input box("From" box) of the "Filter array" action. enter image description here

And then add the filter condition. enter image description here

After running the logic app, it will filter the items by the filter condition. enter image description here

As the filter action don't know how many items match the condition, so the output will always be a array but not an item or a record even if there is only one item matches the condition(label equals "Vehicle Type") in your custom_data_field list.

So if you want to get the value, you need to get it by writing an expression as below screenshot. enter image description here

Hope it helps~

Upvotes: 5

Related Questions