Home>

I have a file like this. I would like to use jq to split this into those with and without the key "h".
Is it possible? I tried using has, but it seems that it only recognizes the top key (a, b, c, d).

[
    {
        "a": 123,
        "b": 456,
        "c": 789,
        "d": [
            {
                "e": 123,
                "f": 456,
                "g": 789
            }
        ]
    },
    {
        "a": 123,
        "b": 456,
        "c": 789,
        "d": {
            "e": 123,
            "f": 456,
            "g": 789,
            "h": 122
        }
    },
    {
        "a": 123,
        "b": 456,
        "c": 789,
        "d": {
            "e": 123,
            "f": 456,
            "h": 122
        }
    }
]


I want to divide this into two and output it.

[
{
        "a": 123,
        "b": 456,
        "c": 789,
        "d": [
            {
                "e": 123,
                "f": 456,
                "g": 789
            }
        ]
    }
]
[
    {
        "a": 123,
        "b": 456,
        "c": 789,
        "d": {
            "e": 123,
            "f": 456,
            "g": 789,
            "h": 122
        }
    },
    {
        "a": 123,
        "b": 456,
        "c": 789,
        "d": {
            "e": 123,
            "f": 456,
            "h": 122
        }
    }
]
  • Answer # 1

    It seems that you should check the type and connect with a comma.

    jq'(. [] | Select ((.d | type) ==" array ") | select (.d [] | .h)), (. [] | select ((.d | type) ==" object ") | select (.d ["h "])))'