使用JQ将同一文件中的多个JSON数组合并为一个JSON数组

时间:2019-10-03 21:28:07

标签: json jq

我有一个文件,其中包含多个单独的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数组中

预先感谢

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

确切的要求对我来说还不太清楚,但是使用以下def会产生预期的结果,并且由于递归可能会引起人们的兴趣:

def peel:
  if type == "array"
  then if length == 0 then empty
       elif length == 1 and (.[0] | type) == "array" then .[0] | peel
       elif all(.[]; type=="array") then .[] | peel
       else [.[] | peel]
       end
  else .
  end;

使用此def和以下“主”程序:

[inputs | peel]

使用-n选项调用jq会产生预期的结果。