gpt4 book ai didi

json - 使用 jq 获取数组的所有值

转载 作者:行者123 更新时间:2023-12-04 03:19:08 25 4
gpt4 key购买 nike

我用 jq 解析一个 json 文件:

jq .response[1].text file.json

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

但是当我这样做时:
jq .response[].text file.json

它给出了一个错误:不能用字符串“text”索引数字

该文件如下所示:

{
"response": [
1000,
{
"id": ,
"date": ,
"owner_id": ,
"from_id": ,
"post_type": "post",
"text": "blabla",
"attachment": {
"type": "photo",
"photo": {
"pid": ,
"aid": -7,
"owner_id":
}
},
"attachments": [
{
"type": "photo",
"photo": {
}
},
{
"type": "link",
"link": {
"url": "",
"title": "",
"description": "",
"target": "external"
}
}
],
"post_source": {
"type": "vk"
},
"comments": {
"count": 0,
"groups_can_post": true,
"can_post": 1
},
},
{
"id": ,
"date": ,
"owner_id": ,
"from_id": ,
"post_type": "post",
"text": "blabla",
"attachment": {
"type": "link",
"link": {
"url": "",
"title": "",
"description": "",
"target": "external",
"
}

最佳答案

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

.response[].text?

另一个是明确检查类型,例如:
.response[] | objects | .text

还有一种可能:
.response[] | select(type=="object" and has("text")) | .text

如果您想在没有“文本”字段时使用占位符值:
 .response[] | if type=="object" and has("text") then .text else null end

所以这真的取决于你的要求,也许你正在使用的 jq 版本。

关于json - 使用 jq 获取数组的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45523425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com