Recursive Nested JSON Key Search
Learn this problemProblem statement
Given a compact JSON string json and a property name targetKey, recursively search every object and array for the first property whose key exactly equals targetKey.
The JSON value tree contains only objects, arrays, and strings. Object properties remain in their textual order, arrays remain in index order, and duplicate property names are allowed.
Use depth-first, left-to-right traversal:
- For an object, visit each property in textual order.
- Visit a property's key before its value. If the key matches, return that property's complete value immediately.
- If the key does not match, recursively search its value before moving to the next property.
- For an array, recursively search elements from index
0upward.
Return the matched value as the exact compact JSON substring from json. A string value therefore includes its surrounding quotation marks. If no key matches, return NOT_FOUND.
Function
findNestedJsonValue(json: String, targetKey: String) → StringExamples
Example 1
json = "{\"departments\":[{\"name\":\"Strategy\",\"lead_strategist\":\"Sarah Chen\"},{\"name\":\"Data\",\"lead_strategist\":\"Omar Ali\"}]}"targetKey = "lead_strategist"return = "\"Sarah Chen\""The first matching property appears in the first department object, so the returned JSON value is the string literal "Sarah Chen".
Example 2
json = "{\"teams\":{\"primary\":{\"team\":\"search\",\"members\":[\"Ada\",\"Lin\"]},\"backup\":{\"team\":\"ads\"}}}"targetKey = "primary"return = "{\"team\":\"search\",\"members\":[\"Ada\",\"Lin\"]}"The matching property stores an object, so the complete compact object value is returned with its original property order.
Example 3
json = "{\"a\":{\"target\":\"deep\"},\"target\":\"shallow\"}"targetKey = "target"return = "\"deep\""Depth-first traversal searches the value of property a before visiting the later root property, so the nested value wins.
Constraints
1 <= json.length <= 200001 <= targetKey.length <= 100jsonis valid compact JSON with no whitespace outside strings.- Every value is an object, array, or string, and the maximum nesting depth is
200. - Strings contain only English letters, digits, spaces, underscores, and hyphens, so no escape sequences occur.
- Property order and duplicate property occurrences are significant.