如何从jq迭代bash中的JSON数组 [英] How to iterate a JSON array in bash from jq
问题描述
我希望能够将json文件传递到WP CLI,以迭代方式创建帖子.
I want to be able to pass a json file to WP CLI, to iteratively create posts.
所以我想我可以创建一个JSON文件:
So I thought I could create a JSON file:
[
{
"post_type": "post",
"post_title": "Test",
"post_content": "[leaflet-map][leaflet-marker]",
"post_status": "publish"
},
{
"post_type": "post",
"post_title": "Number 2",
"post_content": "[leaflet-map fitbounds][leaflet-circle]",
"post_status": "publish"
}
]
并使用jq迭代数组:
cat posts.json | jq --raw-output .[]
我希望能够对它们进行迭代以执行类似的功能:
I want to be able to iterate these to execute a similar function:
wp post create \
--post_type=post \
--post_title='Test Map' \
--post_content='[leaflet-map] [leaflet-marker]' \
--post_status='publish'
有没有办法用 jq
或类似的方法做到这一点?
Is there a way I can do this with jq
, or similar?
到目前为止,我最接近的是:
The closest I've gotten so far is this:
> for i in $(cat posts.json | jq -c .[]); do echo $i; done
但这似乎与字符串中的(有效)空格有关.输出:
But this seems to take issue with the (valid) spaces in the strings. Output:
{"post_type":"post","post_title":"Test","post_content":"[leaflet-map][leaflet-marker]","post_status":"publish"}
{"post_type":"post","post_title":"Number
2","post_content":"[leaflet-map
fitbounds][leaflet-circle]","post_status":"publish"}
我是否会采用这种方法,还是可以做到?
Am I way off with this approach, or can it be done?
推荐答案
使用 while
读取整行,而不是遍历命令替换产生的 words
Use a while
to read entire lines, rather than iterating over the words resulting from the command substitution.
while IFS= read -r obj; do
...
done < <(jq -c '.[]' posts.json)
这篇关于如何从jq迭代bash中的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!