我的数据结构如下:
{
"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/