" 时出现 jq 错误-6ren"> " 时出现 jq 错误-我正在尝试遍历 all 索引中包含的所有元素。这是我的 json 字符串: { "all":[ { "id":"51a" }, -6ren">
gpt4 book ai didi

json - 遍历数组 : Cannot index array with string "" 时出现 jq 错误

转载 作者:太空狗 更新时间:2023-10-29 11:06:44 25 4
gpt4 key购买 nike

我正在尝试遍历 all 索引中包含的所有元素。这是我的 json 字符串:

{  
"all":[
{
"id":"51a"
},
{
"id":"52b"
},
{
"id":"53c"
}
]
}

我尝试使用 jq 进行迭代:

for id in $(jq '.all.id | keys | .[]' <<< "$json"); do
echo "$id"
done

但我收到以下错误:

jq: error (at :9): Cannot index array with string "id"

我希望得到以下输出:

51a
52b
53c

最佳答案

像那样:

for id in $(jq -r '.all[].id' <<< "$json"); do
echo "$id"
done

请注意,如果要删除双引号,必须使用 -r 选项:

 ·   --raw-output / -r:

With this option, if the filter´s result is a string then
it will be written directly to standard output rather than
being formatted as a JSON string with quotes. This can be
useful for making jq filters talk to non-JSON-based
systems.

整个脚本看起来像这样:

#!/usr/bin/env bash

json='{
"all":[
{
"id":"51a"
},
{
"id":"52b"
},
{
"id":"53c"
}
]
}'

for id in $(jq -r '.all[].id' <<< "$json"); do
echo "$id"
done

但如评论中所述,for x in $(...) 是一种反模式,不应使用:https://mywiki.wooledge.org/DontReadLinesWithFor .

将两个索引分配给 2 个单独的变量:

#!/usr/bin/env bash

json='{
"all":[
{
"id":"51a",
"name":"Steve"
},
{
"id":"52b",
"name":"Phoebe"
},
{
"id":"53c",
"name":"Dino"
}
]
}'

jq -r '.all[] | .id + " " + .name' <<< "$json" |
while read -r id name; do
echo id: "$id"
echo name: "$name"
done

关于json - 遍历数组 : Cannot index array with string "<key>" 时出现 jq 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56220762/

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