JSONPath Reader
Difficulty: Medium · Topics: JSON, String Parsing, Recursion · Acceptance: 17.1% of 117 submissions
Difficulty: Medium | Tags: JSON, String Parsing, Recursion
Description
Given a JSON object (as a nested Map / dictionary) and a JSONPath string, return the value located at that path.
JSONPath rules:
$— root object.key— access a property[n]— access array element at indexn
Implement:
getValueByJSONPath(jsonObject, jsonPath) → Object | null
Examples
Example 1:
Input:
json = {"store": {"book": [{"title": "Harry Potter"}, {"title": "LOTR"}]}}
path = "$.store.book[0].title"
Output: "Harry Potter"
Example 2:
Input:
json = {"a": {"b": {"c": 42}}}
path = "$.a.b.c"
Output: 42
Example 3:
Input:
json = {"users": [{"name": "Alice", "scores": [90, 85]}, {"name": "Bob"}]}
path = "$.users[0].scores[1]"
Output: 85
Example 4 — Invalid path:
Input:
json = {"a": 1}
path = "$.a.b.c"
Output: null
Constraints
- JSON nesting depth ≤ 20.
- Array indices are 0-based non-negative integers.
- Path always starts with
$. - If the path is invalid or a key doesn't exist, return
null. - Keys contain only alphanumeric characters and underscores.
Hints
Hint 1
Split the path on . and process each segment left to right.
Hint 2
For segments containing [, split again on [ to separate the key from the index.
Follow-up
- Support wildcard
$.store.book[*].title→ returns an array of all titles. - Support filter expressions
$.store.book[?(@.price < 10)].