Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

jq

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]",    ... ] 
like image 563
danielrvt Avatar asked Apr 03 '17 19:04

danielrvt


People also ask

What is jq command in bash?

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.

How use jq command in Linux?

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.

Does jq use JSONPath?

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.

What is jq in command line?

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.


Video Answer


1 Answers

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.

like image 149
chepner Avatar answered Sep 18 '22 09:09

chepner