Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

iteration

jq

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?

like image 334
Zimbabwe Elephant Avatar asked Feb 28 '16 00:02

Zimbabwe Elephant


1 Answers

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

like image 148
peak Avatar answered Sep 18 '22 04:09

peak