0

I'm really new to Postgres and was wondering if there is an easy way to do this. I have a table where I will only query a single row at a time. Every row is about a product and every column is basic nutritional info on the pack which looks like this:

click here for image

While querying a single row, I want to ignore all the columns that have null values and return the rest in a JSON format. I haven't found a good way to filter the null columns.

I found this is how you convert the data to JSON in Postgres and it works well but because every product (row) will have different nutritional info (column) so I don't how to implement this.

If there is no way to implement this then can I send everything to the frontend and filter it there? Will that affect the performance a lot? I have about 150 columns.

1 Answer 1

3

You can convert the complete row to a JSON value without NULL values using jsonb_strip_nulls()

select jsonb_strip_nulls(to_jsonb(t))
from the_table t
where ...

to_jsonb(t) converts the complete row to a JSON value where the column name is the key. jsonb_strip_nulls() will then remove those keys with a NULL value.

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

1 Comment

This was exactly what I was looking for, can't thank you enough.

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.