JQ создать массив и добавить запись к нему - PullRequest
0 голосов
/ 28 мая 2018

Я хочу создать файл 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 переменные и передать его в файл results.json как запись / за итерацию.

Спасибо

Ответы [ 3 ]

0 голосов
/ 28 мая 2018

Вам действительно нужно записать файл, используя 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 ']'
0 голосов
/ 28 мая 2018

Повторное использование тестовой среды Гленна, но вызов всего одного сценария 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]]}'
0 голосов
/ 28 мая 2018
#!/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"
    ]
  ]
}
...