Understanding recursion in JSONata
Last updated
Last updated
Next, we'll present an example that defines recursion to navigate and transform a JSON structure. This article will detail the initial example and expand it with additional explanations, practical examples and use cases, providing a comprehensive understanding of the application of recursion in JSONata.
The line above defines a recursive function called $person. The function takes a node ($node) as an argument. It returns an object containing:
"n": Name - The Name property of the current node.
"p": $person(Parent.Person) - The result of calling the $person function on the Parent.Person property of the current node, allowing for recursive navigation.
This part applies the $person function to the "Person" field in the current context (denoted by $). The ~> operator pipes the "Person" field through the $person function.
Let's enhance the example by adding more fields for transformation and navigating through more deeply nested JSON structures. Consider the following more complex JSON structure:
Let's modify the function to include the "Age" property and handle cases where "Parent" may be absent.
The modified function now includes "a": Age to capture each person's age.
The ternary operator ($exists($person(Parent.Person)) ? ... : null) ensures the function returns "null" if the node is not present, preventing errors when navigating the hierarchy.
Applying the expanded query to the input JSON example will result in:
Let's consider an example where each person can have siblings.
We can expand our role even further to include brothers:
Explanation
The line "s": $exists($person(Siblings)) ? $person(Siblings) : null maps the Siblings array and transforms each sibling into an object.
Example Output
Applying the expanded query to the input JSON example will result in:
The recursive function in JSONata provides a powerful way to navigate and transform nested JSON structures. By defining and applying such functions, you can traverse hierarchical data, handle optional fields and even map arrays to produce complex, automated transformations.