Output specific key value in object for each element in array with jq for JSON
IterationJqIteration Problem Overview
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?
Iteration Solutions
Solution 1 - Iteration
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".
Solution 2 - Iteration
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
Solution 3 - Iteration
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
Solution 4 - Iteration
An alternative using map
:
jq "map ( .AssetId ) | .[]"