Reputation: 153
I would like to run a bash command for each field in a JSON formatted piece of data by leveraging jq.
{
"apps": {
"firefox": "1.0.0",
"ie": "1.0.1",
"chrome": "2.0.0"
}
}
Basically I want something of the sort:
foreach app:
echo "$key $val"
done
Upvotes: 14
Views: 14515
Reputation: 14655
Here is an bash script which demonstrates a possible solution.
#!/bin/bash
json='
{
"apps": {
"firefox": "1.0.0",
"ie": "1.0.1",
"chrome": "2.0.0"
}
}'
jq -M -r '
.apps | keys[] as $k | $k, .[$k]
' <<< "$json" | \
while read -r key; read -r val; do
echo "$key $val"
done
Example output
chrome 2.0.0
firefox 1.0.0
ie 1.0.1
Upvotes: 5
Reputation: 134841
Assuming you wanted to list out the key/values of the apps
object:
$ jq -r '.apps | to_entries[] | "\(.key)\t\(.value)"' input.json
To invoke another program using the output as arguments, you should get acquainted with xargs:
$ jq -r '...' input.json | xargs some_program
Upvotes: 7