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:

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

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

Practice this problem

Related problems