jq create array并向其添加条目

时间:2018-05-28 19:58:44

标签: bash jq

我想生成具有如下结构的json文件:

{
  "data": [
    [
      "Tiger Nixon",
      "Edinburgh"
    ],
    [
      "Garrett Winters",
      "Tokyo"
    ]
  ]
}

这是我的bash脚本:

list=( http://RESTURL1 http://RESTURL2 )

jq -n .data[] > result.json ## -> (create empty array data)

for p in $list

VAR1=$(curl $p | jq -r .foo ) ## -> (Tiger Nixon)
VAR2=$(curl $p | jq -r .bar ) ## -> (Edinburgh)

cat result.json | jq -n --arg a "$VAR1" --arg b "$VAR2"  .data["$a","$b"] >> results.json ## -> (add Tiger Nixon and Edinburgh to .data array)

done

脚本是自我解释的。除了jq部分。我不知道如何处理jq来创建json文件。

基本上我想迭代url列表,填充2个变量并将其作为entry / per iteration推送到results.json文件。

由于

3 个答案:

答案 0 :(得分:4)

重用Glenn的测试框架,但只为整个脚本调用jq一次:

list=( http://RESTURL1 http://RESTURL2 )

declare -A hypothetical_data=(
    [http://RESTURL1]='{"foo":"Tiger Nixon","bar":"Edinburgh"}'
    [http://RESTURL2]='{"foo":"Garrett Winters","bar":"Tokyo"}'
)

for url in "${list[@]}"; do
  echo "${hypothetical_data[$url]}"  # or curl "$url"
done | jq -n '{"data": [inputs | [.foo, .bar]]}'

答案 1 :(得分:3)

#!/bin/bash

list=( http://RESTURL1 http://RESTURL2 )

declare -A hypothetical_data=(
    [http://RESTURL1]='{"foo":"Tiger Nixon","bar":"Edinburgh"}'
    [http://RESTURL2]='{"foo":"Garrett Winters","bar":"Tokyo"}'
)

# create the seed file
result="result.json"
echo '{"data":[]}' > "$result"

for url in "${list[@]}"; do
    # fetch the data.
    json=${hypothetical_data[$url]}
    # would really do: json=$(curl "$url")

    # extract the name ("foo") and location ("bar") values
    name=$( jq -r '.foo' <<<"$json" )
    location=$( jq -r '.bar' <<<"$json" )

    jq --arg name "$name" \
       --arg loc "$location" \
         '.data += [[$name, $loc]]' "$result" | sponge "$result"

    # "sponge" is in the "moreutils" package that you may have to install. 
    # You can also write that line as:
    #
    # tmp=$(mktemp)
    # jq --arg name "$name" \
    #    --arg loc "$location" \
    #      '.data += [[$name, $loc]]' "$result" > "$tmp" && mv "$tmp" "$result"
    #                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
done

最终结果:

$ cat result.json
{
  "data": [
    [
      "Tiger Nixon",
      "Edinburgh"
    ],
    [
      "Garrett Winters",
      "Tokyo"
    ]
  ]
}

答案 2 :(得分:0)

你真的需要使用jq写文件吗?

list=( http://RESTURL1 http://RESTURL2 )

exec > result.json    

echo '['

for p in "${list[@]}"
    data=$(curl "$p")
    echo "  $(jq -c '[.foo, .bar]' <<< "$data"),"
done

echo ']'