Search code examples
javascriptjsonn8n

If statement within a JSON selection?


In the JSON below, I am attempting to select the raw price value when the price is_rpp = True. This can sometimes be the first price or it can be any of N number of prices listed but most of the time there is none or ONE is_rpp = True price.

Is this possible?

As an example, using {{ $json["price"]["value"] }} does select the price for me but I want the is_rpp = True price.

Thank you

{
    "position": 1,
    "title": "Apple USB-C to Lightning Cable (2 m)",
    "asin": "asintest",
    "link": "https://www.amazon.com/",
    "categories": [{
        "name": "Electronics",
        "id": "electronics"
    }],
    "image": "https://m.media-amazon.com/images/",
    "is_prime": true,
    "rating": 4.8,
    "ratings_total": 15213956,
    "prices": [{
            "symbol": "$",
            "value": 29,
            "currency": "USD",
            "raw": "$29.00",
            "name": "$29.00",
            "is_primary": true
        },
        {
            "symbol": "$",
            "value": 35,
            "currency": "USD",
            "raw": "$35.00",
            "name": "$29.00",
            "is_rrp": true
        }
    ],
    "price": {
        "symbol": "$",
        "value": 29,
        "currency": "USD",
        "raw": "$29.00",
        "name": "$29.00",
        "is_primary": true
    },
    "page": "1",
    "position_overall": 1
}

This will be used within N8N: https://docs.n8n.io/code-examples/expressions/jmespath/#an-alternative-to-arrow-functions


Solution

  • Got it!

    {{ $jmespath($json.prices, "[?is_rrp == `true`] | [0].value") }}