Recursive function to create hierarchical JSON object?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
If you have flat records with parent-child relationships and you want nested JSON, recursion is often the clearest solution. The basic idea is simple: find the children of the current node, build each child recursively, and stop when a node has no children.
A Common Input Shape
Suppose you start with rows like this:
This is flat data, but it describes a tree. The goal is to turn it into nested JSON with children arrays.
Recursive Tree Builder
Here is a straightforward recursive function in JavaScript:
This works because:
- the base case happens naturally when no children are found
- the recursive step builds each child's
childrenarray
The output is hierarchical JSON that mirrors the parent-child structure.
Why Recursion Fits the Problem
Hierarchical data is self-similar:
- a root contains children
- each child may contain children
- each descendant follows the same rule
That is exactly the kind of structure recursion models well. The same function can process the top level and every nested level without special-case code for depth 1, depth 2, and so on.
Python Version
The same pattern works cleanly in Python:
This is the same algorithm expressed in a different language: select children, recurse, stop when no children exist.
Improving Performance for Large Trees
The simple version scans the full list at every recursion level. That is easy to read but not ideal for large datasets.
A better approach is to pre-group rows by parentId:
This keeps recursion but avoids repeated full-list filtering.
Common Pitfalls
The most common mistake is not defining a real base case. Even though the base case can be implicit, the data still needs to terminate cleanly with nodes that have no children.
Another issue is forgetting to guard against cycles. If the input data contains an accidental parent loop, a naive recursive function can recurse forever.
A third pitfall is assuming the root always has parentId = null. Some systems use 0, an empty string, or a separate root marker instead. Match the function to the actual data model.
Finally, for very large trees, repeated filtering can become expensive. Pre-indexing by parent is usually the easiest performance improvement.
Summary
- Recursive tree building is a natural fit for hierarchical JSON generation.
- The core pattern is filter children, map them, and recurse into each child.
- Flat parent-child records can be transformed into nested JSON cleanly with one function.
- Pre-grouping rows by
parentIdimproves performance on larger datasets. - Watch for cycles, root-convention mismatches, and missing termination conditions.
Related reading
- recursive query for adjacency list to preorder tree traversal in SQL?
- Red-black tree over AVL tree
- Red-Black Trees
- Reduce array to set in Swift
- Referencing a string in a string array resource with xml
- Relationship between BFS and topological sort
- Relaxation of an edge in Dijkstra's algorithm
- Removal of negative numbers from an array in Java

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.