简体   繁体   中英

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?

$ 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"
]
jq --raw-output '.StackSummaries[].StackName'

这是另一种解决方案

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM