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

Zimbabwe Elephant picture Zimbabwe Elephant · Feb 28, 2016 · Viewed 52.4k times · Source

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?

Answer

peak picture peak · Feb 28, 2016

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