Ela Ela - 1 month ago 7
JSON Question

Remove all null values

I am trying to remove null values from a json object using jq. I found this issue on their github and so now I'm trying to remove them with

I have this:

'{ id: $customerId, name, phones: ([{ original: .phone },
{ original: .otherPhone}]), email} | del(. | nulls)'

This doesn't seem to do anything. However if I replace
it does remove the phone numbers.


The following illustrates how to remove all the null-valued keys from a JSON object:

jq -n '{"a":1, "b": null, "c": null} | with_entries( select( .value != null ) )'
  "a": 1

By the way, del/1 can also be used to achieve the same result, e.g. as follows:

jq -n '{"a":1, "b": null, "c": null}
  | reduce keys[] as $k (.; if .[$k] == null then del(.[$k]) else . end)'
  "a": 1

And for the record, here's an example of how to use delpaths/1:

jq -n '{"a":1, "b": null, "c": null, "d":2} as $o
  | $o
  | delpaths( [  keys[] | select( $o[.] == null ) ] | map( [.]) )'
  "a": 1,
  "d": 2