如何检查jq中是否有数组或对象?

时间:2021-01-31 07:00:55

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.

例如,我想从键中提取值,但是这个键有时包含一个对象(我的意思是一个值),有时包含一个数组(我的意思是多个值)。如何检查是否有数组或对象?谢谢。

1 个解决方案

#1


11  

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:

示例1:

echo '[0, false, [], {}, null, "hello"]' | jq 'map(type)'
[
  "number",
  "boolean",
  "array",
  "object",
  "null",
  "string"
]

Example 2:

示例2:

echo '[0,1]' | jq 'if type=="array" then "yes" else "no" end'
"yes"

Example 3:

示例3:

echo '{"0":0,"1":1}' | jq 'if type=="array" then "yes" else "no" end'
"no"

#1


11  

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:

示例1:

echo '[0, false, [], {}, null, "hello"]' | jq 'map(type)'
[
  "number",
  "boolean",
  "array",
  "object",
  "null",
  "string"
]

Example 2:

示例2:

echo '[0,1]' | jq 'if type=="array" then "yes" else "no" end'
"yes"

Example 3:

示例3:

echo '{"0":0,"1":1}' | jq 'if type=="array" then "yes" else "no" end'
"no"