1

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",
   ...
]
1

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.

|improve this answer|||||
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
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.