Find JSONPath by Key-Value Search
Difficulty: Hard · Topics: JSON, Recursion, DFS, Stack · Acceptance: 8.3% of 12 submissions
Difficulty: Hard | Tags: JSON, DFS, Stack, Recursion
Description
Given a JSON object, a target key, and a target value, find the JSONPath that leads to the matching key-value pair. Search recursively through nested objects and arrays.
Implement:
findPath(jsonObject, key, value) → String
Return the JSONPath (e.g., $.store.book[0].title) or throw if not found.
Examples
Example 1:
Input:
json = {"store": {"book": [{"title": "HP", "price": 10}, {"title": "LOTR", "price": 15}]}}
key = "title"
value = "LOTR"
Output: "$.store.book[1].title"
Example 2:
Input:
json = {"a": {"b": {"c": 42}}}
key = "c"
value = 42
Output: "$.a.b.c"
Example 3 — Not found:
Input:
json = {"x": 1}
key = "y"
value = 2
Output: Error / Exception — "Invalid key and value"
Constraints
- JSON nesting depth ≤ 20.
- Returns the first match found (DFS order).
- If no match exists, throw an exception or return error.
- Array indices are appended as
[n].
Hints
Hint 1
Use a Stack to track the path segments as you recurse. Push key names and array indices, then reconstruct the path from the stack.
Hint 2
Handle three cases: the value matches directly, the value is a nested object, or the value is a nested array.
---
## String & Data Conversion