JSONATA query to navigate json array using a json property as index

57 views Asked by At

Let's say I have the following JSON

{
 "Fruits" : ["apple", "mango", "banana"];
 "Index" : 2
}

How do i navigate the array "Fruits" such that i could use index as the index number I.e. If i write Fruits[Index], it should give me "banana".

I tried the code mentioned above and I got it always as "no match".

2

There are 2 answers

0
mralex On

When you type an expression inside the filter operator (inside square brackets), you're entering the local context of the entries that you're filtering, and all your expressions become local to each array entry instead of the object root.

To break away from that local context you can use the special $$ variable to access the Index property on the root object.

Here's the solution:

Fruits[$$.Index]

Check it out on the Stedi Playground: https://stedi.link/5gbpkfc

0
Jeff Mercado On

The % operator allows you to access the parent context. You could then get the Index from that.

Fruits[%.Index]

You may also store the index as a variable to later use to index the array.

($i:=Index; Fruits[$i])