Akshit
Akshit

Reputation: 17

How to work with variable/dynamic paths in JSONata?

Consider the source JSON below

{
  "Player1": "Ryan",
  "Player2": "Nathan",
  "score": [
    {
      "match1": {
        "Ryan|Nathan": [
          {
            "Round1": {
              "total": 500
            }
          }
        ]
      }
    }
  ]
}

From here if I need to get the value of total, the JSONata query will look like:

{
    "Score": score.match1.`Ryan|Nathan`[0].Round1.total
}

and the result will be:

{
  "Score": 500
}

How do I modify the path in the query based on the values in the source, like if instead of Ryan and Nathan, the values for Player1 and Player2 were Will and Max respectively, and based on that it was Will|Max, how can I have my query change accordingly?

I tried to first dynamically create a string for the required path but I fail to understand how can I use this string as a path later on.

"score.match1.`" & Player1 & "|" & Player2 & "`[0].Round1.total"

Upvotes: 0

Views: 950

Answers (1)

mralex
mralex

Reputation: 1090

You can use the $lookup function to get value by a dynamically defined key:

{ 
  "Score": $lookup(score.match1, Player1 & "|" & Player2)[0].Round1.total 
}

Check it on the live playground: https://stedi.link/ffGrafH

Upvotes: 0

Related Questions