Graham Leggett
Graham Leggett

Reputation: 1147

Given a json array, how do I extract a list of key values by key, using jq?

I have a json array that looks like this:

{
  "StackSummaries": [
    {
      "CreationTime": "2016-06-01T22:22:49.890Z",
      "StackName": "foo-control-eu-west-1",
      "StackStatus": "UPDATE_COMPLETE",
      "LastUpdatedTime": "2016-06-01T22:47:58.433Z"
    },
    {
      "CreationTime": "2016-04-13T11:22:04.250Z",
      "StackName": "foo-bar-testing",
      "StackStatus": "UPDATE_COMPLETE",
      "LastUpdatedTime": "2016-04-26T16:17:07.570Z"
    },
    {
      "CreationTime": "2016-04-10T01:09:49.428Z",
      "StackName": "foo-ldap-eu-west-1",
      "StackStatus": "UPDATE_COMPLETE",
      "LastUpdatedTime": "2016-04-17T13:44:04.758Z"
    }
  ]
}

I am looking to create text output that looks like this:

foo-control-eu-west-1
foo-bar-testing
foo-ldap-eu-west-1

Is jq able to do this? Specifically, what would the jq command line be that would select each StackName in the array and output each key one per line?

Upvotes: 2

Views: 2466

Answers (3)

jq170727
jq170727

Reputation: 14715

Here is another solution

jq -M -r '..|.StackName?|values' input.json

Upvotes: 0

Robb Edge
Robb Edge

Reputation: 91

jq --raw-output '.StackSummaries[].StackName'

Upvotes: 3

peak
peak

Reputation: 116957

$ jq -r '[.StackSummaries[] | .StackName] | unique[]' input.json
foo-bar-testing
foo-control-eu-west-1
foo-ldap-eu-west-1

The -r option strips the quotation marks from the output. You might not want the call to 'unique'.

For reference, if you wanted all the key names:

$ jq '[.StackSummaries[] | keys[]] | unique' input.json
[
  "CreationTime",
  "LastUpdatedTime",
  "StackName",
  "StackStatus"
]

Upvotes: 3

Related Questions