0

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
  • Are you calling jq from a bash/shell script? That kind of complex munging will get messy fast. I'd write a little Python script in cases like this. Commented Oct 3, 2019 at 22:24
  • the same JSON query alternatively could be achieved using a walk-path unix utility jtc: <input.json jtc -w'<>i:><a[-1]' -J If you like I can elaborate on it in a separate answer. PS. I'm a developer of the jtc unix tool for JSON processing. Commented Oct 4, 2019 at 9:51

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.