0

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.

ayniam
  • 573
  • 2
  • 8
  • 27
  • Well, maybe shell isn't a right tool for the task? Have you considered alternatives like e.g. python? – user3159253 Nov 10 '15 at 04:45
  • no. i want to do it using shell script. i know its possible with jq or similar utilities. i am just facing compile errors – ayniam Nov 10 '15 at 04:46
  • If you insist on using shell script, then at least learn the basics of shell scripting. [Unquoted variables](http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable) and [useless uses of `cat`](http://www.iki.fi/era/unix/award.html) are grave shell scripting antipatterns. – tripleee Nov 10 '15 at 07:38

2 Answers2

4

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
kev
  • 155,172
  • 47
  • 273
  • 272
3

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/ .

Community
  • 1
  • 1
Anon
  • 6,306
  • 2
  • 38
  • 56