如何从 jq 在 bash 中迭代 JSON 数组

boz*_*doz 2 bash json jq wp-cli

背景

我希望能够将 json 文件传递​​给 WP CLI,以迭代地创建帖子。

所以我想我可以创建一个 JSON 文件:

[
    {
        "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"
    }
]
Run Code Online (Sandbox Code Playgroud)

并用 jq 迭代数组:

[
    {
        "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"
    }
]
Run Code Online (Sandbox Code Playgroud)

我希望能够迭代这些以执行类似的功能:

cat posts.json | jq --raw-output .[]
Run Code Online (Sandbox Code Playgroud)

有没有办法用jq或类似的方法来做到这一点?

到目前为止,我得到的最接近的是:

wp post create \
  --post_type=post \
  --post_title='Test Map' \
  --post_content='[leaflet-map] [leaflet-marker]' \
  --post_status='publish'
Run Code Online (Sandbox Code Playgroud)

但这似乎与字符串中的(有效)空格有关。输出:

> for i in $(cat posts.json | jq -c .[]); do echo $i; done
Run Code Online (Sandbox Code Playgroud)

我离这种方法不远了,还是可以做到?

che*_*ner 7

使用 awhile读取整行,而不是迭代命令替换产生的单词

while IFS= read -r obj; do
    ...
done < <(jq -c '.[]' posts.json)
Run Code Online (Sandbox Code Playgroud)