Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding nulls from row_to_json() result in PostgreSQL

I want to convert the rows of a record set to JSON, but not include any null entries that are just going to end up being undefined in JavaScript anyway. For example, suppose I have the table testdata with entries

id | prop1 (integer) | prop2 (text)
-------------------------------------
 1 |               42 | 'Answer'
 2 |             NULL | 'No prop one'
 3 |                0 | NULL

and then execute

SELECT row_to_json(testdata) FROM testdata

What I get is:

{"id":"1","prop1":"42","prop2":"Answer"}
{"id":"2","prop1":null,"prop2":"No prop one"}
{"id":"3","prop1":"0","prop2":null}

But instead, what I want is:

{"id":"1","prop1":"42","prop2":"Answer"}
{"id":"2","prop2":"No prop one"}
{"id":"3","prop1":"0"}

Is this possible? According to the JSON functions documentation for PostgreSQL 9.3, there's only one extra option or parameter for row_to_json, but setting pretty_bool=true doesn't remove the nulls, so it seems as if the answer may be no. But this also seems as if it's a very obvious and useful function, so I'm hoping that somebody else has found something I've missed.

My end goal is to retrieve the records in JavaScript with a GET call to a PHP page. Am I better off building the JSON in PHP from a more standard recordset, instead of using PostgreSQL's JSON routines?

like image 731
Michael Avatar asked Apr 15 '14 20:04

Michael


People also ask

What is -> in PostgreSQL?

PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.

Do NULL values take up space Postgres?

Answer: No, Each null value only uses one bit on disk. In the scheme of things, having a few null columns will not have a major impact on the disk usage. If your database table has 30 such default null fields, it would still only be 30 bits per row.

How do I check if a JSON key exists in Postgres?

In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.


2 Answers

Postgres 9.5 introduces json_strip_nulls function, that seems to do exactly what you want.

like image 96
murison Avatar answered Sep 18 '22 13:09

murison


Looks like future versions of the function may have an 'ignore nulls' option - https://commitfest.postgresql.org/action/patch_view?id=1496

like image 29
T.R. Avatar answered Sep 20 '22 13:09

T.R.