使用jq从未知字符串键属性获取值

时间:2017-07-04 10:38:36

标签: json jq

我的数据结构如下:

{
  "data": {
    "2017-06-20": {
      "shifts": [
        {
          "id": 24,
          "shift_request_id": 24,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 38,
          "shift_request_id": 38,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 85,
          "shift_request_id": 85,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    },
    ...
    ...
    ...
    ...
    "2017-06-21": {
      "shifts": [
        {
          "id": 26,
          "shift_request_id": 26,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 28,
          "shift_request_id": 28,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 88,
          "shift_request_id": 88,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    }
  }
}

因此,对于那些类似日期的格式化密钥,我们想要从第一个这样的密钥中提取shifts。我对通过特定日期提取感兴趣,因为将日期指定为键很容易,而是从整个集合中选择,其中之一或范围,通过数字索引,一旦获得这些键。

我试过了:

jq '.[] | keys'

它给了我一系列所有键,但后来我不知道如何提取由数字索引的特定键的移位数组。

jq '.[] | keys[3]'

会连续给我第四个关键字,但后来.shifts无法解决这个问题,并说Cannot index string with string "shifts"

1 个答案:

答案 0 :(得分:0)

通过查看https://stackoverflow.com/a/34227629/2434479,我能够找到解决这个问题的方法,所以我会把它作为参考,以便在类似的情况下找到自己的人。

所以这样做的一种方法是:

❯ http ... | jq '.[] | to_entries[] | [.key, (.value.shifts | length)] | @csv'

当需要索引的特定键时,请说第4行:

❯ http|curl ... | jq '.[] | keys_unsorted[3] as $k | "\($k), \(.[$k].shifts | length)"'
相关问题