Build a Collapsible JSON Tree Renderer in React
Data Structure DesignModel answerLast 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:
- Accept a JSON string as a prop and parse it safely, showing an error message if the input is malformed
- Display primitives (strings, numbers, booleans, null) as leaf nodes with appropriate formatting
- Render objects and arrays as expandable/collapsible containers with toggle controls
- Handle arbitrary nesting depth through a recursive component structure
- 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a Collapsible JSON Tree Renderer
This problem tests your ability to translate a recursive data structure into a component hierarchy, manage local state effectively, and handle untrusted input safely.
Component Architecture
The solution uses three components that mirror the structure of JSON data:
JsonViewer (root component): Accepts the JSON string prop, parses it once using useMemo, handles parse errors, and renders the top-level value. This separation keeps parsing logic and error boundaries at the entry point.
JsonNode (recursive renderer): Renders a single JSON value. For primitives, it delegates to Primitive. For containers (objects/arrays), it renders a toggle button, opening delimiter, recursive child nodes, and closing delimiter. This is where recursion happens—each child value spawns a new JsonNode.
Primitive (leaf formatter): Formats terminal values correctly. Strings must be quoted and escaped; numbers, booleans, and null render as-is. Using JSON.stringify(value) for strings ensures correct escape sequences.
State Management
Each container node maintains its own expanded state via useState(true). This design choice provides:
- Independence: Toggling one node doesn't affect siblings or ancestors
- Localized updates: Only the toggled subtree re-renders, not the entire tree
- Simplicity: No prop drilling or context needed
Trade-off: When a node collapses, its children unmount and lose their own expansion state. If you need features like "expand all descendants" or persistent state across parent toggles, lift state to the root as a Map<path, boolean> where paths are JSON Pointer strings like /school or /nicknames/0. Pass isExpanded(path) and togglePath(path) down as props. This enables global operations but requires memoization to prevent unnecessary re-renders.
Safe Parsing and Rendering
Parsing: JSON.parse is safe—it never executes code—but throws on invalid input. Wrapping it in try/catch converts parse failures into rendered error messages rather than crashed components. The useMemo hook ensures parsing happens only when the input changes, not on every toggle.
Rendering: All text goes through React's JSX escaping. Keys and string values pass through JSON.stringify, which correctly handles quotes, backslashes, and unicode. This ensures the output matches valid JSON syntax and prevents any injection issues.
Input validation: The function checks that the input is actually a string before attempting to parse, catching type errors early.
Complexity Analysis
Parse: O(n) time and O(n) space where n is the input string length. Happens once per input change.
Initial render: O(V) where V is the number of visible nodes. Collapsed subtrees don't render at all, which is the primary performance optimization—a deeply nested but collapsed branch adds zero render cost.
Toggle operation: O(S) where S is the size of the subtree being shown or hidden. When expanding, React must mount all descendants. When collapsing, it unmounts them.
Memory: O(V) for React elements plus O(D) for the recursion stack depth.
For very large documents, you could optimize by:
- Automatically collapsing nodes beyond a depth threshold
- Virtualizing large arrays (render only visible elements)
- Paginating array children ("show 100 more")
Edge Cases and Considerations
Invalid JSON: Show a clear error message. Note that JavaScript object literals like {name: "bob"} (unquoted keys) are not valid JSON and will fail parsing.
Primitive root: Input like "42" or "null" is valid JSON. Render a single leaf node without a toggle.
Empty containers: {} and [] render inline without a toggle since there's nothing to expand.
Special characters in keys: Keys containing quotes, backslashes, or unicode escape correctly through JSON.stringify.
Deep nesting: Thousands of levels can exhaust the call stack. For pathological cases, consider a depth limit or an iterative flattening approach.
Duplicate keys: JSON.parse keeps the last occurrence, which is standard behavior.
Commas: The isLast prop ensures commas appear only between siblings, matching JSON syntax.
Implementation
import { useMemo, useState } from "react";
function parseJson(text) {
if (typeof text !== "string") {
return { ok: false, error: "Input must be a string" };
}
try {
return { ok: true, value: JSON.parse(text) };
} catch (e) {
return { ok: false, error: e.message };
}
}
function Primitive({ value }) {
if (value === null) return <span className="null">null</span>;
if (typeof value === "string") {
return <span className="string">{JSON.stringify(value)}</span>;
}
return <span className="number">{String(value)}</span>;
}
function JsonNode({ name, value, depth, isLast }) {
const [expanded, setExpanded] = useState(true);
const comma = isLast ? "" : ",";
const keyLabel = name !== undefined ? (
<span>
<span className="key">{JSON.stringify(name)}</span>:{" "}
</span>
) : null;
const isContainer = value !== null && typeof value === "object";
if (!isContainer) {
return (
<div style={{ marginLeft: depth * 20 }}>
{keyLabel}
<Primitive value={value} />
{comma}
</div>
);
}
const isArray = Array.isArray(value);
const entries = isArray
? value.map((v, i) => [i, v])
: Object.entries(value);
const [open, close] = isArray ? ["[", "]"] : ["{", "}"];
if (entries.length === 0) {
return (
<div style={{ marginLeft: depth * 20 }}>
{keyLabel}
{open}
{close}
{comma}
</div>
);
}
return (
<div>
<div style={{ marginLeft: depth * 20 }}>
<button onClick={() => setExpanded(e => !e)} className="toggle">
{expanded ? "▾" : "▸"}
</button>{" "}
{keyLabel}
{open}
{!expanded && (
<span>
…{close}
{comma} <span className="count">
{entries.length} {isArray ? "items" : "keys"}
</span>
</span>
)}
</div>
{expanded && (
<>
{entries.map(([k, v], i) => (
<JsonNode
key={k}
name={isArray ? undefined : k}
value={v}
depth={depth + 1}
isLast={i === entries.length - 1}
/>
))}
<div style={{ marginLeft: depth * 20 }}>
{close}
{comma}
</div>
</>
)}
</div>
);
}
export function JsonViewer({ json }) {
const result = useMemo(() => parseJson(json), [json]);
if (!result.ok) {
return (
<div className="error">
Parse error: {result.error}
</div>
);
}
return (
<pre className="json-viewer">
<JsonNode value={result.value} depth={0} isLast={true} />
</pre>
);
}
What Interviewers Evaluate
- Recursive thinking: Recognizing that JSON's recursive structure naturally maps to recursive components
- State placement: Understanding when to use local state versus lifted state
- Input validation: Not trusting external data, using safe parsing, and handling errors gracefully
- Attention to detail: Correct JSON syntax (quotes, escapes, commas), handling edge cases
- Performance awareness: Explaining render complexity and optimization strategies
- Communication: Stating assumptions clearly (e.g., "the example input isn't valid JSON as written") and explaining trade-offs
Strong candidates implement a working solution, explain why it's correct, identify at least one optimization or alternative approach, and acknowledge limitations.