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:
1.<span></span>Should become:
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.