arrays - jq - 在 JSON 对象中查找数组的名称,然后获取数组的内容
问题描述
我有以下 JSON 数组
[
{
"city": "Seattle",
"array10": [
"1",
"2"
]
},
{
"city": "Seattle",
"array11": [
"3"
]
},
{
"city": "Chicago",
"array20": [
"1",
"2"
]
},
{
"city": "Denver",
"array30": [
"3"
]
},
{
"city": "Reno",
"array50": [
"1"
]
}
]
我的任务如下:对于每个"city"
已知的值,获取数组的名称,对于每个数组,打印/显示其内容。城市和数组的名称是唯一的,数组的内容 - 不是。
结果应如下所示:
Now working on Seattle
Seattle has the following arrays:
array10
array11
Content of the array10
1
2
Content of the array11
3
Now working on Chicago
Chicago has the following arrays:
array20
Content of the array array20
1
2
Now working on Denver
Denver has the following arrays:
array30
Content of the array array30
3
Now working on Reno
Denver has the following arrays:
array50
Content of the array array50
1
现在,对于每个城市名称(提供/已知),我可以使用以下过滤器找到数组的名称(我可以将城市名称放在变量中):
jq -r .[] | select ( .name | test("Seattle") ) | del (.name) | keys |@tsv
然后将这些名称分配给一个 bash 变量并在新的循环中迭代以获取每个数组的内容。
虽然我可以通过上述方式得到我想要的,但我的问题是 - 有没有更有效的方法来使用 jq 呢?
第二个相关问题 - 如果我的 JSON 具有以下结构,从速度/效率/简单性的角度来看,它是否会使我的任务更容易?
[
{
"name": "Seattle",
"content": {
"array10": [
"1",
"2"
],
"array11": [
"3"
]
}
},
{
"name": "Chicago",
"content": {
"array20": [
"1",
"2"
]
}
},
{
"name": "Denver",
"content": {
"array30": [
"3"
]
}
},
{
"name": "Reno",
"content": {
"array50": [
"1"
]
}
}
]
解决方案
使用 -r 命令行选项,以下程序产生如下所示的输出:
group_by(.city)[]
| .[0].city as $city
| map(keys_unsorted[] | select(test("^array"))) as $arrays
| "Now working on \($city)",
"\($city) has the following arrays:",
$arrays[],
(.[] | to_entries[] | select(.key | test("^array"))
| "Content of the \(.key)", .value[])
输出
Now working on Chicago
Chicago has the following arrays:
array20
Content of the array20
1
2
Now working on Denver
Denver has the following arrays:
array30
Content of the array30
3
Now working on Reno
Reno has the following arrays:
array50
Content of the array50
1
Now working on Seattle
Seattle has the following arrays:
array10
array11
Content of the array10
1
2
Content of the array11
3
推荐阅读
- applescript - AppleScript - 语法错误:预期的行尾但找到“””
- python-3.x - 使用 numpy 数组比较两个相似的 PIL 图像不起作用
- python - 更改 seaborn pairplot 对角线颜色
- scala - Scala 是否可以异步运行循环?
- java - java中斐波那契堆consolidate方法的实现,IndexofBoundsException的错误
- asp.net - 如何在aspx页面中获取请求值
- c - scanf() 的 char 函数采用 \n 输入而不是 char?
- node.js - 持久化 NodeJS 套接字
- python - Python 中的 Selenium 代码会产生语法错误
- javascript - 如何使用jQuery删除空格字符后的文本?