Using the awesome jmespath with filter expressions to get a value from an array with a specific key

Hi there fellow n8n-ers,

So I recently tried the cool addition of jmespath for n8n. It’s awesome! So with a tool like:
https://api.gopipeline.io/jmespath-tester

you can input some json and try your query. Which works great. So for instance you have this interesting filter feature as described here:
https://jmespath.org/tutorial.html


which would make filtering json by key name and getting the value much easier. So I tried this with tester and it works great:

with this json:

[
    {
        "number": "159784",
        "meta_data": [
            {
                "id": 3274100,
                "key": "_billing_house_number",
                "value": "14"
            },
            {
                "id": 3274101,
                "key": "_billing_house_number_suffix",
                "value": ""
            },
            {
                "id": 3274102,
                "key": "_billing_street_name",
                "value": "some street name"
            },
            {
                "id": 3274103,
                "key": "_billing_em_ver",
                "value": "[email protected]"
            },
            {
                "id": 3274104,
                "key": "_shipping_house_number",
                "value": "14"
            },
            {
                "id": 3274105,
                "key": "_shipping_house_number_suffix",
                "value": ""
            },
            {
                "id": 3274106,
                "key": "_shipping_street_name",
                "value": "some street"
            },
            {
                "id": 3274107,
                "key": "is_vat_exempt",
                "value": "no"
            }
        ]
        }
]

and this query:
[0].meta_data[?key==’_billing_house_number’].value

It outputs [14], which is ALMOST what I need. Because it returns an array now, not just a single value. So now you just add | [0] to output only the first value et voila:

It tooks some trial and error to find out how this works in n8n, but here you go. Just use the Set node and here is the code:

{{$jmespath($json.meta_data, "[?key=='_billing_house_number'].value | [0]")}}

and it works!

Obviously you can use any key name you need and do a lot of other stuff with this cool jmespath. But as a new community member I thought I should share this! This saves a ton of javascripting!

3 Likes

@Jelle_de_Rijke great! And just in case you missed this JMESPath functionality

1 Like

Thanks for sharing :slight_smile: