给定一个json数组,如何使用jq按键提取键值列表?

时间:2016-07-12 15:19:54

标签: arrays json jq

我有一个看起来像这样的json数组:

{
  "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"
    }
  ]
}

我希望创建如下所示的文本输出:

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

jq是否能够做到这一点?具体来说,jq命令行会选择数组中的每个StackName并每行输出一个键吗?

3 个答案:

答案 0 :(得分:2)

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

-r选项从输出中删除引号。您可能不希望拨打“&unique;'。

。”

供参考,如果您想要所有的关键名称:

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

答案 1 :(得分:2)

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

答案 2 :(得分:0)

这是另一种解决方案

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