jsonselectjqempty-list

Remove empty results with jq


I want to remove the empty results and it currently looks like this

{
  "profile": "test1",
  "services": [
    {
      "name": "app",
      "version": "1.3.2"
    }
  ]
}
{
  "profile": "test2",
  "services": []
}

I don't want test2 to be presented since it's empty. This is the command im currently running

cat data.json | jq '.[] | {profile: .profile, services: [.clusters[].services[]| select(.taskdef[] | .name=="app" and .version=="1.3.2") | .taskdef[] ]}'

And this a sample of data.json

[{
    "profile": "test1",
    "clusters": [{
            "cluster": "test1-cluster1",
            "services": [{
                "servicename": "cluster1-service",
                "taskdef": [{
                    "name": "app",
                    "version": "1.3.3"
                }]
            }]
        },
        {
            "cluster": "test1-cluster2",
            "services": [{
                "servicename": "cluster2-service",
                "taskdef": [{
                    "name": "app",
                    "version": "1.3.2"
                }]
            }]
        }
    ]
},
{
    "profile": "test2",
    "clusters": [{
        "cluster": "test2-cluster1",
        "services": [{
            "servicename": "cluster1-service",
            "taskdef": [{
                "name": "app",
                "version": "1.4.0"
            }]
        }]
    }]
}

]

I have been experimenting with select( lenght > 0) but i cant get the syntax correct.


Solution

  • You could simply append the following to your existing pipeline:

    | select(.services!=[])
    
    

    Or you could rewrite the query:

    .[]
    | [.clusters[].services[] 
       | select(.taskdef[] | .name=="app" and .version=="1.3.2") 
       | .taskdef[] ] as $services
    | select($services!=[])
    | {profile, $services}