← Questions

Collapsible JSON viewer in React

0
NotionCodingLast asked Jul 2025

A coding interview question asked in Notion's technical phone screen, last asked Jul 2025. It tests frontend, react and recursion.

In an hour of React, build a component that takes a JSON string and shows it as a pretty-printed, read-only tree. Every nested object and array gets a toggle (such as a caret) that collapses it to a short placeholder and expands it again. Nesting can go to any depth.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • <JsonViewer json={string} /> — parses the string and renders the tree.
  • Objects show {, one key: value line per entry, }; arrays show [, one line per item, ]; children are indented one level.
  • A collapsed object shows {…} (or { 2 keys }) and a collapsed array […], with the toggle still visible.
  • Strings render in quotes; numbers, booleans and null as they are.
  • Invalid JSON shows an error message instead of crashing.

Example

Input:

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

Rendered, all expanded:

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

After clicking the toggle on school:

  ▸ school: {…}

Constraints

  • Arbitrary nesting; documents of a few thousand nodes should stay responsive.

Clarifying questions

  • Start expanded or collapsed? Should collapse state survive a change of the input?
  • Should empty objects and arrays have a toggle?
  • Is the input always a string, or sometimes an already parsed value?
  • Any requirements for keyboard use or screen readers?

What a strong answer covers

  • A recursive JsonNode component that switches on the value's type (object, array, primitive) and renders children with depth for indentation.
  • Where the collapsed state lives: local useState in each node (simple, but lost when the input changes) or one Set of collapsed paths in the parent (supports "collapse all" and survives re-renders). Choose one and say why.
  • Parsing in useMemo with try/catch, and an error message for bad input.
  • Stable keys from object keys or array indexes, empty {} and [] without toggles, and the toggle as a real button with aria-expanded.
  • Cost: rendering is linear in visible nodes; collapsed subtrees are not rendered at all.

Follow-ups

  • Add "expand all" and "collapse all".
  • Make a 10 MB document usable: virtualize the visible lines.
  • Add search that expands the path to every match and highlights it.

Where it's asked

What it tests

frontend · react · recursion

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding