Search code examples
jsonjslt

jslt how to reference element from parent node


I am trying to calculate some variables using jslt. I have a json similar to this:

{
"total_amount": 5349,
"total_amount_currency": "USD",
"latest_reservation_date": "05-24-2022",
"reservations":[

    "reservation1": {
        "amount": "3284",
        "currency": "USD",
        "reservation_date": "02-14-2021",
        "countries_visited": [
            "country1": {"Malaysia"},
            "country2": {"Singapore"},
            "country3": {"Brunei"}
        ]
    },
    "reservation2": {
        "amount": "2065",
        "currency": "USD",
        "reservation_date": "05-24-2022",
        "countries_visited": [
            "country1": {"South Africa"},
            "country2": {"Namibia"}
        ]
    }
]
}

and, while iterating the "countries_visited" array, I would like to reference an element in the parent node, say "reservation_date", but I not know how to. Thanks in advance for any help!!


Solution

  • JSLT doesn't have an operator for traversing to the parent node, because this allows us to have better performance by reusing input nodes in the output tree.

    The easiest way to solve this is to put a reference to the parent in a variable before you do the loop. Then you can refer to the variable inside the loop, and everything will work.