KatInterview

Build a Collapsible JSON Tree Renderer in React

Data Structure DesignModel answer
MediumModel answerData Structure Designreactrecursioncomponent-design

Last updated

Create a React component that parses a JSON string and displays it as an interactive, expandable tree structure.

Design and implement a React component that takes a JSON string as input and renders it as an interactive tree viewer. The component should display the JSON structure in a readable format where users can expand or collapse nested objects and arrays.

Your implementation must:

  1. Accept a JSON string as a prop and parse it safely, showing an error message if the input is malformed
  2. Display primitives (strings, numbers, booleans, null) as leaf nodes with appropriate formatting
  3. Render objects and arrays as expandable/collapsible containers with toggle controls
  4. Handle arbitrary nesting depth through a recursive component structure
  5. Track expansion state independently for each container node

For demonstration purposes, test your component with this JSON structure (properly formatted as a valid JSON string):

{
  "name": "bob",
  "age": 5,
  "nicknames": ["bobby", "bobman"],
  "school": {
    "name": "bob university",
    "year": 2015
  }
}

The viewer should allow toggling the school object and the nicknames array independently.

In your response, explain:

  • How your component hierarchy maps to the JSON structure
  • Where and why you placed component state
  • How you ensure safe parsing and rendering
  • Time and space complexity of key operations (parse, render, toggle)
  • Any significant edge cases and trade-offs

Hints

Hint 1

Map the recursive data structure directly to recursive React components—each JSON value becomes a component instance

Hint 2

Place expand/collapse state at the container level so each node controls its own visibility independently

Hint 3

Use JSON.parse with try/catch for safe parsing, and JSON.stringify to correctly escape strings and keys