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

前端 未结 2 1074
半阙折子戏
半阙折子戏 2021-01-13 08:51

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         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 09:01

    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;
    

提交回复
热议问题