簡體   English   中英

使用 JQ 將同一文件中的多個 JSON 數組合並為一個 JSON 數組

[英]Combine multiple JSON array in same file into one JSON array using JQ

我有一個文件,其中包含多個單獨的 JSON arrays,我想將其組合(並刪除空數組)到單個 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"
        ]
    ]
]

需要 output

[
    [
        "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 arrays,我想將其組合(並刪除空數組)到單個 JSON 數組中

提前致謝

這僅選擇非空 arrays 的元素都不是數組,並將它們放入數組中:

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

確切的要求對我來說不是太清楚,但是使用以下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 會產生預期的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM