首页 > 解决方案 > 使用 JQ 将同一文件中的多个 JSON 数组合并为一个 JSON 数组

问题描述

我有一个文件,其中包含多个单独的 JSON 数组,我想将它们组合(并删除空数组)到单个 JSON 数组中

输入

[]
[]
[
    [
        [
            "asdfsdfsdf",
            "CCsdfnceR1",
            "running",
            "us-east-1a",
            "34.6X.7X.2X",
            "10.75.170.118"
        ]
    ]
]
[]
[]
[
    [
        [
            "tyutyut",
            "CENTOS-BASE",
            "stopped",
            "us-west-2b",
            null,
            "10.87.159.249"
        ]
    ],
    [
        [
            "tyutyut",
            "dfgdfg-TEST",
            "stopped",
            "us-west-2b",
            "54.2X.8.X8",
            "10.87.159.247"
        ]
    ]
]

所需输出

[
    [
        "asdfsdfsdf",
        "CCsdfnceR1",
        "running",
        "us-east-1a",
        "34.6X.7X.2X",
        "10.75.170.118"
    ],
    [
        "tyutyut",
        "CENTOS-BASE",
        "stopped",
        "us-west-2b",
        null,
        "10.87.159.249"
    ],
    [
        "tyutyut",
        "dfgdfg-TEST",
        "stopped",
        "us-west-2b",
        "54.2X.8.X8",
        "10.87.159.247"
    ]
]

我有一个文件,其中包含多个单独的 JSON 数组,我想将它们组合(并删除空数组)到单个 JSON 数组中

提前致谢

标签: jsonjq

解决方案


这仅选择元素都不是数组的非空数组,并将它们放入数组中:

jq -n '[ inputs | .. | select(type=="array" and .!=[] and all(.[]; type!="array")) ]' file

推荐阅读