solemnify
solemnify

Reputation: 153

Running bash commands for each JSON item through jq

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

Answers (2)

jq170727
jq170727

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

Jeff Mercado
Jeff Mercado

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

Related Questions