【问题标题】:How to iterate a JSON array in bash from jq如何从 jq 在 bash 中迭代 JSON 数组
【发布时间】:2019-03-01 21:47:02
【问题描述】:

背景

我希望能够将 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"
    }
]

并用 jq 迭代数组:

cat posts.json | jq --raw-output .[]

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

wp post create \
  --post_type=post \
  --post_title='Test Map' \
  --post_content='[leaflet-map] [leaflet-marker]' \
  --post_status='publish'

我有什么方法可以使用jq 或类似方法来做到这一点?

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

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

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

{"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"}

我用这种方法是否可行,或者可以做到吗?

【问题讨论】:

  • c.f. stedolan.github.io/jq/manual - -c 明确表示要挤出空格,例如换行符。在循环内尝试--indent n,但-c 会生成您的数据。循环使用while read -r i;do echo "$i"|jq --indent 2 '.'; echo "==="; done < <( jq -c '.[]' posts.json )

标签: json bash jq wp-cli


【解决方案1】:

使用while 读取整行,而不是遍历命令替换产生的单词

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

【讨论】:

  • 好主意。在偶然发现您的解决方案之前,我一生都无法完成这项工作
【解决方案2】:

也许这对你有用:

制作一个 bash 可执行文件,可以称之为 wpfunction.sh

#!/bin/bash

wp post create \
  --post_type="$1"\
  --post_title="$2" \
  --post_content="$3" \
  --post_status="$4"

然后在您的posts.json 上运行jq 并将其通过管道传输到xargs

jq -M -c '.[] | [.post_type, .post_title, .post_content, .post_status][]' \
posts.json | xargs -n4 ./wpfunction`

我正在尝试看看这将如何处理包含引号的 post_content...

【讨论】:

    【解决方案3】:

    首先生成一个您希望传递的参数数组,然后使用@sh 转换为与shell 兼容的形式。然后你可以传递给 xargs 来调用命令。

    $ jq -r '.[] | ["post", "create", (to_entries[] | "--\(.key)=\(.value|tojson)")] | @sh' input.json | xargs wp
    

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 2014-04-21
      • 1970-01-01
      • 2011-03-07
      • 2020-02-26
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多