Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove null values from a postgres jsonb array?

Given a jsonb field with a value of

{
  values: [null, 'test', { key: 'value' }]
}

is it possible to return an output of

{
  values: [ 'test', { key: 'value' }]
}

Ive looked at the docs and have found some functions like jsonb_strip_nulls() which this only works for keys with null values and array_remove() which I cannot get to work with jsonb.

I would use

UPDATE table 
  SET data = jsonb_set(data, '{values}'::text[], jsonb_agg(elem), false)
FROM data, 
     jsonb_array_elements(data-> 'values') WITH ORDINALITY AS t(elem, nr)
WHERE jsonb_typeof(elem) <> 'null'
GROUP BY (data.id)

and this would work correctly for mose cases, but I need it to work with the case:

{
  values: [null, null, null]
}

the above query does not return

{
  values: []
}

in this case.

Any help is appriciated!! Thanks...

like image 904
Dalaigh88 Avatar asked Aug 29 '26 20:08

Dalaigh88


1 Answers

For PostgreSQL 12:

select jsonb_path_query_array('{"values": [null, "test", { "key": "value" }]}', '$.values[*] ? (@ != null)')    
like image 164
Alexey Orlov Avatar answered Aug 31 '26 15:08

Alexey Orlov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!