Flatten a Nested JSON Object

viaLeetCode

Problem: Write code to read a nested JSON object and flatten it into dot-notation key-value pairs.

Example: Input:

a: {
  a1: 123,
  a2: {
    b: "abc",
    c: 32
  }
}

Output:

a.a1 = 123
a.a2.b = "abc"
a.a2.c = 32

Approach: Recursively walk the object: for each key, if the value is itself an object, recurse into it while appending the current key (joined by '.') to the prefix; if the value is a primitive, emit the accumulated dotted key with that value. O(n) in the total number of leaf keys.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account