I can perform
SELECT to_json(1)
SELECT to_json(1.4)
SELECT to_json(\'this is a nice json text\')
SELECT to_json(\'{\"become\":\"json\"}\')
SELECT to_json(\'n
Pavel Stehule's answer is great, and has led me to a simpler solution:
SELECT 'null'::json;
to_json
is marked as STRICT
function, it is mean - returning NULL when any parameter is NULL. I am not sure if it is correct implementation, maybe it is PostgreSQL bug.
Update: After discussion on Postgres' mailing list this is not the bug, but feature - the situation is not simple due fact, so both languages support NULL, but the behave of NULL is little bit different in any from these languages. It is hard to decide if SQL NULL have to be immediately transformed to JSON NULL and lost a SQL behave immediately. If you need different behave, you can use a SQL function:
CREATE OR REPLACE FUNCTION to_json2(anyelement)
RETURNS json AS $$
SELECT COALESCE(to_json($1), json 'null')
$$ LANGUAGE sql;