Skip to content
RED SAGSkills

Flatten Nested JSON Keys

Given a JSON object obj, return a flat object whose keys are the paths to every leaf value, joined with .. Array elements use their index as the path segment, so {"a":[5]} becomes {"a.0":5}.

A leaf is any value that is not an object or array (string, number, boolean, null), or an empty object or empty array, which is kept as is.

Example 1

Input: obj = {"a":1,"b":{"c":2,"d":{"e":3}}}
Output: {"a":1,"b.c":2,"b.d.e":3}

Example 2

Input: obj = {"user":{"name":"Ana","tags":["x","y"]}}
Output: {"user.name":"Ana","user.tags.0":"x","user.tags.1":"y"}

Constraints

  • The input is a plain JSON object (not an array).
  • Nesting depth <= 50.
  • Keys do not contain the . character.
Hint 1

Recurse with the path built so far.

Hint 2

Arrays are objects too: Object.keys on an array gives its indexes as strings.

Discussion 0

Join free to post in the discussion.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Data Engineer, Automation Test Engineer, Mobile App Developer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.