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

标签 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]'

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

最佳答案

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

关于json - 使用 jq 从未知字符串键属性获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44903686/

相关文章:

javascript - D3js 与 json 错误

c# - 如何在不使用 foreach 循环的情况下获取 JObject 的第一个子对象

json - 如何在jq walk中引用父对象?

php - 如何在 iOS 中获取 JSON 响应?获得零值(value)?

c++ - 如何让 boost json 使用正确的数据类型

json - `select (. == ["a","b"][])` 谓词在 JQ 中如何工作?

stream - 添加非数组格式的数字?或者如何过滤到数组以便我可以总结

MySQL 无法检测 jq 生成的 CSV 中的换行符

json - Bash 在另一个变量中存储 json 响应

java - 在 RESTful Web 服务中使用 @Consumes(MediaType.APPLICATION_JSON) 时出现问题