李智明 发表于 2023-9-13 14:27:32

如何查询JSON列中的空对象?

寻找所有的行,其中某个json列包含一个空对象{}。对于JSON数组,或者在对象中寻找特定键,这是可能的。但是我只想知道对象是否为空。似乎找不到可以执行此操作的运算符。
dev=# \d test
   Table "public.test"
Column | Type | Modifiers
--------+------+-----------
foo    | json |
dev=# select * from test;
    foo
---------
{"a":1}
{"b":1}
{}
(3 rows)
dev=# select * from test where foo != '{}';
ERROR:operator does not exist: jsonunknown
LINE 1: select * from test where foo != '{}';
                                    ^
HINT:No operator matches the given name and argument type(s). You might need to add explicit type casts.
dev=# select * from test where foo != to_json('{}'::text);
ERROR:operator does not exist: jsonjson
LINE 1: select * from test where foo != to_json('{}'::text);
                                    ^
HINT:No operator matches the given name and argument type(s). You might need to add explicit type casts.
dwv=# select * from test where foo != '{}'::json;
ERROR:operator does not exist: jsonjson
LINE 1: select * from test where foo != '{}'::json;
                                    ^
HINT:No operator matches the given name and argument type(s). You might need to add explicit type casts.
               
解决方案:
               


                有没有平等(或等于)运算符的数据类型json作为一个整体,因为平等是很难建立。jsonb在可行的情况下,请考虑使用Postgres 9.4或更高版本。有关dba.SE(上一章)的此相关答案中的更多详细信息:
如何从PostgreSQL的JSON []数组中删除已知元素?
SELECT DISTINCT json_column ...或... GROUP BY json_column由于相同原因而失败(没有相等运算符)。
将表达式的两边都转换为textallow=或operator,但这通常并不可靠,因为对于相同的JSON值,有很多可能的文本表示形式。
但是,对于这种特殊情况(空对象),它可以正常工作:
select * from test where foo::text'{}'::text;
页: [1]
查看完整版本: 如何查询JSON列中的空对象?