为什么在 postgreSQL 中不能将 NULL 转换为 JSON 的 null?

Onz*_*nza 6 postgresql json

我可以表演

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')
Run Code Online (Sandbox Code Playgroud)

并且一切正常,但是当您执行以下操作时:

SELECT to_json(NULL::TEXT)
Run Code Online (Sandbox Code Playgroud)

你实际上得到的Postgres内置NULL,就像如果没有真的发生了,当我期待的结果相同to_json('null')的exapleSELECT to_json(someText)::TEXT FROM ...也许,你所期望的"input""stuff"""null,而是你会得到"input""stuff"""

我的问题是,为什么SELECT to_json(NULL::TEXT)不给你一个 json null,而是一个 NULL 指针?为什么它在 postgres 中是这样实现的?一些具体的原因?

Pav*_*ule 5

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;
Run Code Online (Sandbox Code Playgroud)