使用循环中的jq将json对象作为来自json数组文件的POST数据

时间:2018-05-22 02:03:01

标签: bash jq

这是我的示例test.json文件

[
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    },
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    },
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    }
]

这是bash脚本

declare -A values=( )
while IFS= read -r value; do
  echo "Read  $value" >&2
  #echo $value | curl -d @- -H "Content-Type: application/json" https://example.com/api/foo
done < <(jq -r '.[]' <$1)

这是我得到的输出

Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }
Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }
Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }

我想在文件中使用JSON对象,使用curl将数据POST到API。我希望循环运行三次。

如何获取整个JSON对象(导致循环运行3次)而不是从test.json文件中输出每一行?

1 个答案:

答案 0 :(得分:2)

使用jq -c,在单独的行中发出每个结果。当您的预期输出是JSON而不是原始字符串时,不要使用-r

我还在下面添加了一些引号,但代码中缺少这些引号:

# for readability, factored out
args=( -d @- -H "Content-Type: application/json"  )

while IFS= read -r value; do
  echo "Read  $value" >&2
  curl "${args[@]}" https://example.com/api/foo <<<"$value"
done < <(jq -c '.[]' <"$1")