用jq获取数组的所有值

Mis*_*ena 9 parsing json jq

我用jq解析一个json文件:

jq .response[1].text file.json
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是每次我必须输入数字.response [2] .text,.response [3] .text等时,我想一次获取所有值(200个值)

但是当我这样做时:

jq .response[].text file.json
Run Code Online (Sandbox Code Playgroud)

它给出了一个错误:无法使用字符串“ text”索引数字

该文件如下所示:

jq .response[1].text file.json
Run Code Online (Sandbox Code Playgroud)

pea*_*eak 14

显然,数组中的一项是字符串。如果您的jq支持“?”,则一种可能性是使用它:

.response[].text?
Run Code Online (Sandbox Code Playgroud)

另一个方法是显式检查类型,例如:

.response[] | objects | .text
Run Code Online (Sandbox Code Playgroud)

还有另一种可能性:

.response[] | select(type=="object" and has("text")) | .text
Run Code Online (Sandbox Code Playgroud)

如果要在没有“文本”字段时使用占位符值:

 .response[] | if type=="object" and has("text") then .text else null end
Run Code Online (Sandbox Code Playgroud)

因此,这实际上取决于您的要求以及您所使用的jq的版本。