Search code examples
jsonnulljqkey-valuejsonlines

Filter empty and/or null values with jq


I have a file with jsonlines and would like to find empty values.

{"name": "Color TV", "price": "1200", "available": ""}
{"name": "DVD player", "price": "200", "color": null}

And would like to output empty and/or null values and their keys:

available: ""
color: null

I think it should be something like cat myexample | jq '. | select(. == "")', but is not working.


Solution

  • The tricky part here is emitting the keys without quotation marks in a way that the empty string is shown with quotation marks. Here is one solution that works with jq's -r command-line option:

    to_entries[]
    | select(.value | . == null or . == "")
    | if .value == "" then .value |= "\"\(.)\"" else . end
    | "\(.key): \(.value)"
    

    Once the given input has been modified in the obvious way to make it valid JSON, the output is exactly as specified.