Running bash commands for each JSON item through jq

10,100

Solution 1

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

Solution 2

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
Share:
10,100
solemnify
Author by

solemnify

Updated on June 08, 2022

Comments

  • solemnify
    solemnify almost 2 years

    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
    
  • solemnify
    solemnify over 7 years
    What if I wanted to actually run a tool against those values, ie: foreach app: mytool $key $val done
  • s.meijer
    s.meijer over 7 years
    @JeffMercado a little more explanation to that comment would be most welcome. Let's say @solemnify is trying to run a command like apt-get install ${APP} -y. What whould the xargs format be?
  • Jeff Mercado
    Jeff Mercado over 7 years
    @s.meijer: I'd say check the manpages for it. But that one should be simple. You could do something like: jq '"filter to select package names"' input.json | xargs -i apt-get install {} -y
  • Marcin
    Marcin over 5 years
    Given the quoting/bracketing cruft in json this is unlikely to work as expected unless some_program takes only 1 argument.