Coding - Nested Map Path Query (JSON Parser)
You are given a nested object in memory, represented as a Map<String, Object> (or Python dict[str, object]).
Implement a function query that takes in a nested map and a string path, and returns the value at the end of the path.
Input:
map = { "a": 1, "b": { "c": 2, "d": 3 } } path = "b.c"
Output: 2
Input:
map = { "a": 1, "b": { "c": 2, "d": 3 } } path = "b.d"
Output: 3
Input:
map = { "a": 1, "b": { "c": 2, "d": 3 } } path = "a"
Output: 1
null or an appropriate error value.`python def query(map, path): keys = path.split('.') current_map = map for key in keys: if isinstance(current_map, dict) and key in current_map: current_map = current_map[key] else: return None return current_map
map = { "a": 1, "b": { "c": 2, "d": 3 } } print(query(map, "b.c")) # Output: 2 print(query(map, "b.d")) # Output: 3 print(query(map, "a")) # Output: 1 `
This solution splits the input path into individual keys, then iterates through the keys to traverse the nested map. If a key is not found at any point, it returns None. Otherwise, it returns the value at the end of the path.