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?
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.
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.
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.
Postgres 9.5 introduces json_strip_nulls
function, that seems to do exactly what you want.
Looks like future versions of the function may have an 'ignore nulls' option - https://commitfest.postgresql.org/action/patch_view?id=1496
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With