Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How check if there is an array or an object in jq?

Tags:

json

jq

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.

like image 377
Fran Avatar asked Aug 10 '15 05:08

Fran


People also ask

How do you check if an object is an array or not?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

How do you check if an object is an array in TypeScript?

To check if a value is an array of specific type in TypeScript: Use the Array. isArray() method to check if the value is an array.

How do you check if a variable is an array in jQuery?

isArray()" to check whether the element is Java script array or not. jQuery. isArray() returns a boolean value that indicates whether the object is a JavaScript array or not. It takes the variable name as an argument and returns the result back to caller.

How do you check if it's an array in JavaScript?

The isArray() method returns true if an object is an array, otherwise false .


2 Answers

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"
like image 104
Hans Z. Avatar answered Oct 13 '22 10:10

Hans Z.


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 | .[] | ...
like image 42
Brewster Kahle Avatar answered Oct 13 '22 10:10

Brewster Kahle