2

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, .email' | mycommand -u {user} -d {date} -e {email}

This doesn't seem to work. How can I take the parameters out of the json array into my command?

My json file looks something like this:

[
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "myemail@domain.com",
   ...
]
danielrvt
  • 239
  • 5
  • 13

2 Answers2

2

Here is an solution based on my answer to a similar question on Stack Overflow.

#!/bin/bash
json='
[
  {
   "user": "danielrvt",
   "date": "11/10/1988",
   "email": "myemail@domain.com"
  }, 
  {
   "user": "anotheruser",
   "date": "1/1/1970",
   "email": "anotheruser@domain.com"
  }
]
'

jq -M -r '
    .[] | .user, .date, .email
' <<< "$json" | \
while read -r user; read -r date; read -r email; do
   echo "$user $date $email"
done

Example output

danielrvt 11/10/1988 myemail@domain.com
anotheruser 1/1/1970 anotheruser@domain.com

In your case you could replace the use of <<< "$json" with < credentials.json and the echo "$user $date $email" with mycommand -u "$user" -d "$date" -e "$email" as appropriate but this should make clear the basic idea.

jq170727
  • 236
  • 3
  • 4
0

you can use a for loop, for example

#!/bin/bash

JSONARRAY=$(cat credentials.json | jq -r '.[] | .user, .date, .email' | mycommand -u {user} -d {date} -e {email} | grep -v "[\|]")
for line in $JSONARRAY; do
    some command
done
Diego Velez
  • 825
  • 1
  • 7
  • 13