skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search