Convert Flat CSV (id, parentId) into Nested Hierarchical JSON using Recursion

Difficulty: EASYCategory: LLDFrequency: 1Asked On 2025-04-13

Problem Statement

Design and implement a program that converts a flat CSV file containing hierarchical relationships (id, parentId) into a nested JSON structure. The solution must use recursion to build the hierarchy.


Background


1.<span></span>Many datasets (like org charts, category trees, filesystem metadata) are stored in a flat tabular form where each record contains an id and a parentId.
2.<span></span>To make the data more useful for APIs or visualization, we often need to convert it into a tree-like JSON structure.
3.<span></span>Example:
<div><div>bash</div><div>CopyEdit</div><div>id,parentId,name</div><div>1,,Electronics</div><div>2,1,Computers</div><div>3,2,Laptops</div><div>4,2,Desktops</div><div>5,1,Mobile Phones</div></div>
1.<span></span>Should become:
<div><div>json</div><div>CopyEdit</div><div>[</div><div> {</div><div> "id": 1,</div><div> "name": "Electronics",</div><div> "children": [</div><div> {</div><div> "id": 2,</div><div> "name": "Computers",</div><div> "children": [</div><div> { "id": 3, "name": "Laptops", "children": [] },</div><div> { "id": 4, "name": "Desktops", "children": [] }</div><div> ]</div><div> },</div><div> {</div><div> "id": 5,</div><div> "name": "Mobile Phones",</div><div> "children": []</div><div> }</div><div> ]</div><div> }</div><div>]</div></div>


Functional Requirements


1.<span></span>Input
2.<span></span>A CSV file with at least these columns:
3.<span></span>id (unique identifier)
4.<span></span>parentId (nullable; empty means root node)
5.<span></span>name (or other attributes to include in JSON)
6.<span></span>Output
7.<span></span>A nested JSON structure representing the parent-child hierarchy.
8.<span></span>Each node should include:
9.<span></span>id, name, children (list of nested objects).
10.<span></span>Implementation Constraints
11.<span></span>Must use recursion to build the tree (not just iterative grouping).
12.<span></span>Handle multiple root nodes (forest structure).
13.<span></span>Handle arbitrary depth of nesting.


Additional Requirements


1.<span></span>Support CSVs with 10⁵ rows (optimize recursion to avoid stack overflow if needed).
2.<span></span>Detect and handle invalid input (e.g., missing parentId reference).
3.<span></span>Provide both:
4.<span></span>In-memory function (csvToNestedJson(data))
5.<span></span>File-to-file utility (input CSV → output JSON).


Deliverables


1.<span></span>A recursive function to build JSON from flat data.
2.<span></span>Unit tests covering:
3.<span></span>Single root
4.<span></span>Multiple roots
5.<span></span>Deeply nested hierarchies
6.<span></span>Orphan nodes (parentId not found)
7.<span></span>Example input CSV and output JSON.


Solution

Comments