Reputation: 351
For example, I want to extract the values from a key, but that key sometimes contains an object (I mean just one value) or sometimes contains an array (i mean multiples values). HOw check if there is an array or there is an object? thanks.
Upvotes: 34
Views: 25341
Reputation: 5648
A more concise, but probably slightly slower:
... | [.] | flatten(1) | ...
So, if it's not an array, it now is. If it is, strip the layer off we just added
Upvotes: 1
Reputation: 181
I have fields that are sometimes strings sometimes arrays and I want to iterate over them. This handles this case:
... | if type=="string" then [.] else . end | .[] | ...
Upvotes: 17
Reputation: 53928
Use the type
function:
type
The type function returns the type of its argument as a string, which is one of null, boolean, number, string, array or object.
Example 1:
echo '[0, false, [], {}, null, "hello"]' | jq 'map(type)'
[
"number",
"boolean",
"array",
"object",
"null",
"string"
]
Example 2:
echo '[0,1]' | jq 'if type=="array" then "yes" else "no" end'
"yes"
Example 3:
echo '{"0":0,"1":1}' | jq 'if type=="array" then "yes" else "no" end'
"no"
Upvotes: 40