Read a value by JSON path
Our own `get(obj, 'orders[1].items[0].sku', default)` – parsing a simple path, telling "missing" from `null` and validating the syntax.
API responses are often deeply nested and chains like a && a.b && a.b[0] && … quickly become unreadable. Let's write a function that reads a value by a text path and returns a default when anything along the way is missing.
Task
getPath(data, path, defaultValue) (Python: get_path(data, path, default=None)):
- a path consists of keys separated by dots (
user.address.city) and indices in brackets (items[0],[2].name,matrix[1][0]), - a key is a non-empty string without
.,[and]; an index is an integer ≥ 0 written in digits, - keys are read only from objects (dicts), indices only from arrays (lists); anything else (a string, a number,
null/None, the wrong container type) means the value is missing, - in JS/TS only own properties count (
toStringorconstructorfrom the prototype are missing), - missing anywhere along the way → return
defaultValue(by defaultundefined/None), - a value that exists is returned even if it is
null,0,falseor an empty string, - an empty path returns
data, - invalid syntax (
a..b,.a,a.,a[x],a[-1],a[,a],[],a.[0]) →Error/ValueErrorwith a message containingInvalid path.
Examples
For data = { user: { name: 'Ola', tags: ['admin', 'dev'], manager: null }, orders: [{ id: 7 }, { id: 9, items: [{ sku: 'X1' }] }] }:
path | defaultValue | Result |
|---|---|---|
"user.name" | – | "Ola" |
"orders[1].items[0].sku" | – | "X1" |
"user.tags[5]" | "none" | "none" |
"user.manager" | "none" | null – the value exists |
"user.manager.name" | "none" | "none" |
"user..name" | – | Invalid path exception |
Constraints
- Paths up to 2,000 segments, JSON-like data (objects/dicts, arrays/lists, strings, numbers, booleans,
null).
Expected complexity
O(p) time, where p is the path length; O(p) memory for the segments.