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

前端 未结 5 1515
眼角桃花
眼角桃花 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:30

    With xargs:

    curl localhost:8082/connectors | jq .[] | xargs -L1 -I'{}' curl -XDELETE 'localhost:8082/connectors/{}' 
    

    Or equivalently, to show the output of that first curl:

    echo '["quickstart-file-sink4","quickstart-file-source","quickstart-file-sink","quickstart-file-sink2","quickstart-file-sink3","quickstart-file-source2"]' | jq .[] | xargs -L1 -I'{}' curl -XDELETE 'localhost:8082/connectors/{}' 
    

    jq .[] strips off one level of containment, so that a list becomes output as one line per item.

    xargs -L1 processes one line at a time

    xargs -I'{}' specifies that the string {} be replaced with the input line when invoking the following command.

    xargs is essentially a map operator for the shell.

提交回复
热议问题