首页 > 解决方案 > 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"
            ]
        }
    }
]

标签: arraysjsonsortingselectjq

解决方案


使用 -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

推荐阅读