Zimbabwe Elephant
Zimbabwe Elephant

Reputation: 1091

Output specific key value in object for each element in array with jq for JSON

I have an array:

[
    {
        "AssetId": 14462955,
        "Name": "Cultural Item"
    },
    {
        "AssetId": 114385498,
        "Name": "Redspybot"
    },
    {
        "AssetId": 29715011,
        "Name": "American Cowboy"
    },
    {
        "AssetId": 98253651,
        "Name": "Mahem"
    }
]

I would like to loop through each object in this array, and pick out the value of each key called AssetId and output it. How would I do this using jq for the command line?

Upvotes: 93

Views: 125091

Answers (5)

Afsar Ali
Afsar Ali

Reputation: 605

For your case jq -r '.[].AssetId' should work

You can also use online JQ Parser : https://jqplay.org/

enter image description here

If you want to loop through the each value then can use below :

for i in $(echo $api_response | jq -r ".[].AssetId")
  do
    echo echo $i 
  done

Upvotes: 4

erhun
erhun

Reputation: 3649

You can also do it via this command.

jq ".[].AssetId" input.json

if array like be that which is in my case

{  
   "resultCode":0,
   "resultMsg":"SUCCESS",
   "uniqueRefNo":"111222333",
   "list":[  
      {  
         "cardType":"CREDIT CARD",
         "isBusinessCard":"N",
         "memberName":"Bank A",
         "memberNo":10,
         "prefixNo":404591
      },
      {  
         "cardType":"DEBIT CARD",
         "isBusinessCard":"N",
         "memberName":"Bank A",
         "memberNo":10,
         "prefixNo":407814
      },
      {  
         "cardType":"CREDIT CARD",
         "isBusinessCard":"N",
         "memberName":"Bank A",
         "memberNo":10,
         "prefixNo":413226
      }
   ]
}

you can get the prefixNo with below jq command.

jq ".list[].prefixNo" input.json

For more specific case on array iterating on jq you can check this blogpost

Upvotes: 30

Chris Stryczynski
Chris Stryczynski

Reputation: 33861

An alternative using map:

jq "map ( .AssetId ) | .[]"

Upvotes: 5

Alexander Oh
Alexander Oh

Reputation: 25601

you have a couple of choices to do the loop itself. you can apply peak's awesome answer and wrap a shell loop around it. replace echo with the script you want to run.

via xargs

$ jq -r ".[] | .AssetId" input.json | xargs -n1 echo  # this would print
14462955
114385498
29715011
98253651

via raw loop

$ for i in $(jq -r ".[] | .AssetId" input.json)
  do
    echo $i
  done
14462955
114385498
29715011
98253651

Upvotes: 8

peak
peak

Reputation: 116640

The command-line tool jq writes to STDOUT and/or STDERR. If you want to write the .AssetId information to STDOUT, then one possibility would be as follows:

jq -r ".[] | .AssetId" input.json

Output:

14462955
114385498
29715011
98253651

A more robust incantation would be: .[] | .AssetId? but your choice will depend on what you want if there is no key named "AssetId".

Upvotes: 112

Related Questions