Pointers and references: Difference between revisions
Content added Content deleted
m (→{{header|jq}}: simplify) |
(→{{header|jq}}: disambiguation) |
||
Line 1,008: | Line 1,008: | ||
all(.[]; type == "string" or (type == "number" and floor == .)); |
all(.[]; type == "string" or (type == "number" and floor == .)); |
||
# The JSON Pointer spec allows 0 both for indexing an array and for retrieving a key named "0". |
|||
⚫ | |||
# disambiguate($k) accordingly disambiguates $k w.r.t. `.`. |
|||
# $k should be a string or integer. |
|||
# If $k is a string and . is an object then: if has($k) then $k else null end. |
|||
# If $k is an integer and . is an array, then emit $k. |
|||
# If $k is an integer-valued string and . is an array then exit $k|tonumber. |
|||
# Otherwise emit null |
|||
def disambiguate( $k ): |
|||
if ($k|type) == "string" |
|||
then if type == "object" then $k |
|||
elif type == "array" and ($k|test("^[0-9]+$")) |
|||
then ($k|tonumber) |
|||
else null |
|||
end |
|||
elif ($k|type) == "number" and type == "array" |
|||
then $k |
|||
else null |
|||
end; |
|||
# $array should be an array of strings and integers. |
|||
# Emit the disambiguated array, suitable for running getpath/1. |
|||
# Emit null if disambiguation fails at any point. |
|||
def disambiguatePath($array): |
|||
. as $in |
|||
| reduce $array[] as $x ([]; |
|||
if . then . as $path |
|||
| ($in | getpath($path) | disambiguate($x)) as $y |
|||
| if $y then . + [ $y ] |
|||
else null |
|||
end |
|||
else . |
|||
end); |
|||
⚫ | |||
def getjsonpointer($pointer): |
def getjsonpointer($pointer): |
||
. as $in |
|||
# first decode ~1, then ~0 |
# first decode ~1, then ~0 |
||
($pointer | split("/") | .[1:] |
| ($pointer | split("/") | .[1:] |
||
| map(gsub("~1"; "/") | gsub("~0"; "~") |
| map(gsub("~1"; "/") | gsub("~0"; "~"))) as $array |
||
| disambiguatePath($array) as $apath |
|||
| getpath($jqpath); |
|||
| if $apath then getpath($apath) else null end; |
|||
# like getpath() but allow $p to be a jsonpointer or an array |
# like getpath() but allow $p to be a jsonpointer or an array |