2

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.

4
  • 1
    I don't think there's a function for this, but you can replace {} and [] by null and then strip nulls again Commented Apr 29, 2019 at 19:19
  • I don't know how to apply that solution either. Commented May 2, 2019 at 12:58
  • 1
    dbfiddle.uk/… Commented May 2, 2019 at 18:51
  • Perfect. It's definitely good enough to be an answer to this question! Commented May 3, 2019 at 7:45

1 Answer 1

1

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.

db<>fiddle demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.