Arrays jq—在JSON对象中找到数组的名称,然后获取数组的内容
我有以下JSON数组Arrays jq—在JSON对象中找到数组的名称,然后获取数组的内容,arrays,json,sorting,select,jq,Arrays,Json,Sorting,Select,Jq,我有以下JSON数组 [ { "city": "Seattle", "array10": [ "1", "2" ] }, { "city": "Seattle", "array11": [
[
{
"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
现在,对于每个城市名称(已提供/已知),我可以使用以下过滤器查找阵列名称(我可以将城市名称放入变量中):
然后将这些名称分配给一个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[])
输出
您将决定使用哪种JSON格式的第一版还是第二版?答案应该基于哪个版本?@Inian,最有效/最简单的版本,但我不知道,这就是为什么我问这两个问题。我已经有了自己的第1个版本的解决方案,但是如果第2个版本的JSON解决方案更简单/更容易,那么我需要首先将第1个版本转换为第2个版本,并对其应用过滤器/解决方案。
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