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": "[email protected]", ... ]
jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.
The JQ command is used to transform JSON data into a more readable format and print it to the standard output on Linux. The JQ command is built around filters which are used to find and print only the required data from a JSON file.
JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.
jq is a lightweight and flexible command-line JSON processor. If you are a command line addict, you will like the official description. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
Your best bet is probably to output each record in something like TSV format, then read that from a shell loop.
jq -r '.[]|[.user, .date, .email] | @tsv' | while IFS=$'\t' read -r user date email; do mycommand -u "$user" -d "$date" -e "$email" done
jq
itself doesn't have anything like a system
call to run an external command from within a filter, although it seems that they are working on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With