Write getPath(obj, path), which reads a nested value out of untrusted data (for example parsed JSON) using a path such as "a.b[0].c".
Path grammar:
- A path is one or more steps. A key is one or more characters, none of which is
.,[or]. An index is one or more ASCII digits. - The first step is either a key (
a) or an index in brackets ([0]). - Every later step is either
.followed by a key, or[index]. - Nothing else is allowed. For example
"","a..b",".a","a.","a[x]","a[","a[]"and"a[0]b"are invalid and fail with{ kind: "invalid_path", path }. The path is validated before any data is read, so an invalid path fails whateverobjis.
Reading:
- A key step applies only to an object that is not an array, and only to its own properties. Anything inherited (such as
toStringorconstructor) does not count. - An index step applies only to an array, and only to an index less than its length.
- If a step does not apply (the current value is
null,undefined, a primitive, the wrong kind of container, or the key or index is not there), the result is absent. - A final value of
nullorundefinedis absent. Every other value, including0,false,"", empty arrays and empty objects, is present and returned as is.