Using jq with bash to run command for each object in array

前端 未结 5 1668
眼角桃花
眼角桃花 2021-02-02 07:48

How can I run a Bash command for every JSON object in a JSON array using jq? So far I have this:

cat credentials.json | jq -r \'.[] | .user, .date, .         


        
5条回答
  •  情书的邮戳
    2021-02-02 08:31

    Here is another variation which I based on the answer from @chepner.

    echo "$config" | jq -c '.[]' |
    while IFS=$"\n" read -r c; do
        echo "start"
        host=$(echo "$c" | jq -r '.host')
        echo $host
        echo "end"
    done
    

    I used jq's -c option to output "compact" jsons, so they are all on one line.

    In combination with IFS=$"\n", I was able to loop over each item in the input json's array and do what I wanted to do.

    So, with an input of

    [
     {
      "host": "host1",
      "settings": {}
     },
     {
      "host": "host1",
      "settings": {}
     }
    ]
    

    the output is

    start
    host1
    end
    start
    host2
    end
    

提交回复
热议问题