Juan Piaggio
Juan Piaggio

Reputation: 190

How to remove an empty object from a json file

I have a json file that looks like this:


[
    [
        [
            {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "10000",
                "self": "https://test.atlassian.net/rest/api/latest/issue/10000",
                "key": "AGILE-1",
                    "components": [],
                    "timetracking": {}

            }
        ]
    ]
]

I'd like to remove the empty arrays like timetracking and components.

I was reading a lot on line and tried different things, but I only manage to remove null or empty values, but the whole array or object.

This is what I tried:

cat $FilePathOrigin | jq-win64.exe -sc 'fromstream(tostream | select(length == 1 or .[1] != null))' > $FilePathDestiny

Upvotes: 2

Views: 1596

Answers (1)

peak
peak

Reputation: 116880

As observed in the comments, it's not entirely clear what you want, but if you want to remove the keys that have values equal to [] or {}, then you could use walk like so:

walk(if type == "object" 
     then with_entries(if .value == {} or .value == [] then empty else . end) 
     else . end)

This can also be written more compactly as:

walk(if type == "object" then with_entries(select(.value | (. != {} and . != []))) else . end)

If you only want to remove keys from specific objects, then the simplest would probably be to use with_entries as above.

Warning about length

length is not only defined on arrays and objects!

Upvotes: 3

Related Questions