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

Fra*_*ran 10 json jq

例如,我想从键中提取值,但该键有时包含一个对象(我只是一个值)或有时包含一个数组(我的意思是倍数值).请问检查是否有阵列或有物体?谢谢.

Han*_* Z. 15

使用type功能:

type
type函数将其参数的类型作为字符串返回,该字符串是null,boolean,number,string,array或object之一.

例1:

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

例2:

echo '[0,1]' | jq 'if type=="array" then "yes" else "no" end'
"yes"
Run Code Online (Sandbox Code Playgroud)

例3:

echo '{"0":0,"1":1}' | jq 'if type=="array" then "yes" else "no" end'
"no"
Run Code Online (Sandbox Code Playgroud)


小智 6

我的字段有时是字符串有时是数组,我想遍历它们。这处理这种情况:

... | if type=="string" then [.] else . end | .[] | ...
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说是完全相同情况的解决方案,只是它有时是对象,有时是数组,而“|” if type!="array" then [.] else 。end |` 更通用 (2认同)