ayniam
ayniam

Reputation: 595

Iterate over a json using shell

I have a json in the following format. I want to iterate over this json file

 {
     "atest_engine": { "version": "96" }, 
     "a_kdfvm": { "version": "68" }, 
     "aseft_api": { "version": "" },
     "push_psservice": { "version": "68" },
   }

I tried jq utility and my script is as follows.

count=$( jq '. | length' test.json )
echo $count
for((i=0;i<$count;i++)) 
do 
 name=$(cat test.json | jq '.|keys['${i}']')
 version=$(cat test.json | jq '.|keys['${i}'].version')
 echo $name
 echo $version
done

I am getting count and name properly but not able to fetch version information. How can I get it. I am new to scripting and any help in this regard is greatly appreciated.Thanks in Advance.

Upvotes: 0

Views: 2595

Answers (2)

kev
kev

Reputation: 161954

input.json

{
     "atest_engine": { "version": "96" }, 
     "a_kdfvm": { "version": "68" }, 
     "aseft_api": { "version": "" },
     "push_psservice": { "version": "68" }
}

command

jq -r 'to_entries[] | "\(.key)\t\(.value.version)"' input.json |
  while read name version
  do
    echo "name:" $name
    echo "version:" $version
  done

result

name: atest_engine
version: 96
name: a_kdfvm
version: 68
name: aseft_api
version:
name: push_psservice
version: 68

Upvotes: 4

Anon
Anon

Reputation: 7174

First up your JSON example seems slightly malformed - the push_psservice line has a comma after it but this is most likely a typo.

You might find it easier to turn your object's fields into an array using jq's to_entries (see https://stackoverflow.com/a/24254365/4513656 ) e.g.:

to_entries | .[0].key
to_entries | .[0].value.version

Try this on https://jqplay.org/ .

Upvotes: 3

Related Questions