Syntax
json.getPath(object: table, path: string | table, defaultValue?: any): any | nilAliases
json.getpathArguments
| Name | Type | Description |
|---|---|---|
object | table | Root table to read from. The function requires this argument to be a table. |
path | string | table | Path to follow. A string is split on dots; integer string tokens are read with raw array indexing. A table path uses its array entries from 1 with #path as keys. |
defaultValue? | any | Fallback value returned when traversal reaches nil or a non-table before the path is complete. |
Returns
| Name | Type | Description |
|---|---|---|
pathValue | any | nil | Value at the requested path. If the path is missing, returns defaultValue when it was provided, otherwise nil. |
Description
Reads a nested value from a table using a dotted string path or an array table of keys.
Call it with 3 parameter(s): object, path, defaultValue. The argument table explains which values are required and which ones only refine the behavior.
It returns pathValue (any | nil). Use the returns table to separate successful values from nil results and recoverable errors.
Example
Read a nested table value from a dotted string path or an array table of keys.
local document = {
user = {
profile = { name = "Guest" },
items = { "first", "second" },
},
}
local name = json.getPath(document, { "user", "profile", "name" }, "Unknown")
local second = json.getPath(document, "user.items.2")
print(name)
print(second)