Excluding nulls from row_to_json() result in PostgreSQL

json, postgresql

Solution

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

Problem

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?

Original source