gpt4 book ai didi

json - Postgres to-json 将复合类型转换为空结构

转载 作者:行者123 更新时间:2023-11-29 12:04:53 26 4
gpt4 key购买 nike

在下面的代码示例中,postgresql (9.4) 应该将复合类型的局部变量转换为 json 字符串。显然 postgresql 处理的空值变量不同于转换为相同类型的空值。

在我的应用程序中,我有嵌套的复合类型,并且希望在复合类型的变量具有 null 作为值时检索 null。

我希望你们中的一些人能帮我解决这个问题。

CREATE TYPE mytype AS (
id SMALLINT,
name TEXT
);

DO $$
DECLARE
l_var mytype;
BEGIN
l_var := NULL;
RAISE INFO '%',to_json(NULL::mytype);
RAISE INFO '%',to_json(l_var) ;
END $$;

--Output
INFO: <NULL>
INFO: {"id":null,"name":null}

最佳答案

是的,PostgreSQL 区分带空字段的 ROW 和 NULL。修复应该不难 - 你应该使用 CASE 表达式:

postgres=# DO $$
DECLARE
l_var mytype;
BEGIN
l_var := NULL;
RAISE INFO '%',to_json(NULL::mytype);
RAISE INFO '%',to_json(CASE WHEN l_var IS NULL THEN NULL ELSE l_var END) ;
END $$;
INFO: <NULL>
INFO: <NULL>
DO

关于json - Postgres to-json 将复合类型转换为空结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30069105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com