【问题标题】:obtain value from unknown string key property, using jq使用 jq 从未知字符串键属性中获取值
【发布时间】:2017-12-07 19:00:06
【问题描述】:

我的数据结构如下:

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

会给我连续第 4 个键,但随后 .shifts 将不起作用,说它是 Cannot index string with string "shifts"

【问题讨论】:

    标签: json jq


    【解决方案1】:

    通过查看此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)"'
    

    【讨论】:

      猜你喜欢
      • 2019-04-11
      • 2020-09-29
      • 2010-11-14
      • 2012-10-30
      • 1970-01-01
      • 2011-04-12
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多