519dsd
519dsd

Reputation: 17

Combine multiple JSON array in same file into one JSON array using JQ

I have a file which has multiple individual JSON arrays, which I want to combine (and remove empty arrays) into a single JSON array

Input

[]
[]
[
    [
        [
            "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"
        ]
    ]
]

Required 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"
    ]
]

I have a file which has multiple individual JSON arrays, which I want to combine (and remove empty arrays) into a single JSON array

Thanks in advance

Upvotes: 0

Views: 225

Answers (2)

peak
peak

Reputation: 117007

The exact requirements aren't too clear to me but using the following def produces the expected result and might be of interest as it is recursive:

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;

With this def, and the following "main" program:

[inputs | peel]

an invocation of jq using the -n option produces the expected result.

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50805

This selects only non-empty arrays none of whose elements is an array, and puts them into an array:

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

Upvotes: 1

Related Questions