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

前端 未结 2 1076
半阙折子戏
半阙折子戏 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:00

    Pavel Stehule's answer is great, and has led me to a simpler solution:

    SELECT 'null'::json;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题