Why can't NULL be converted to JSON null in postgreSQL?

I can execute

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('null')

And everything works correctly, however, when you do:

SELECT to_json(NULL::TEXT)

You actually get postgres builtin NULL, for example, if nothing really happened when I was expecting the same result as to_json('null')for exaple SELECT to_json(someText)::TEXT FROM ..., perhaps you would expect "input", "stuff", ""and null, but instead you get "input", "stuff", ""and

My question is why SELECT to_json(NULL::TEXT)doesn't json give you null, but instead just a NULL pointer? why was this implemented as in postgres? some specific reasons?

+3
source share
2 answers

to_json STRICT, NULL, NULL. , , , PostgreSQL.

: Postgres , - - , NULL, NULL . , SQL NULL JSON NULL SQL. , SQL:

CREATE OR REPLACE FUNCTION to_json2(anyelement)
RETURNS json AS $$
SELECT COALESCE(to_json($1), json 'null')
$$ LANGUAGE sql;
+3

Stehule , :

SELECT 'null'::json;
0

Source: https://habr.com/ru/post/1652646/


All Articles