Reputation: 9398
I stip all the nulls using json_strip_nulls
easily but it causes to have some empty objects on the results:
{
"id": 1,
"organization_id": 1,
"pairing_id": 1,
"location": {},
"device": {
"tracking_id": 1
},
"events": [
{}
]
}
Is there any simple way to remove the empty objects too? In here location and the empty object in events are have to be removed. You can find the complete examples with test data here in DB Fiddle.
Upvotes: 2
Views: 2283
Reputation: 117636
In your certain example I'd suggest to add a couple of helper functions:
create or replace function json_object_nullif(
_data json
)
returns json
as $$
select nullif(json_strip_nulls(_data)::text, '{}')::json
$$ language sql;
create or replace function json_array_nullif(
_data json
)
returns json
as $$
select nullif(_data::text, '[null]')::json
$$ language sql;
and then adjust your view, so instead of json_build_object(...)
you can use json_object_nullif(json_build_object(...))
and the same for json_agg
.
Upvotes: 1