Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 677
solemnify Avatar asked Aug 05 '16 01:08

solemnify


1 Answers

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
like image 125
jq170727 Avatar answered Oct 15 '22 13:10

jq170727