小编典典

如何在json列中查询空对象?

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: json <> unknown
 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: json <> json
 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: json <> json
 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.

阅读 295

收藏
2020-07-27

共1个答案

小编典典

没有平等(或等于)运算符 的数据类型 json 作为一个整体,因为平等是很难建立。
jsonb

在可行的情况下,请考虑使用Postgres 9.4或更高版本。有关dba.SE(上一章)的相关答案中的更多详细信息:

SELECT DISTINCT json_column ...... GROUP BY json_column由于相同的原因失败(没有相等运算符)。

将表达式的两边都转换为textallow =<>operator,但这通常不可靠,因为 同一 JSON值可能有很多文本表示形式。

但是 ,对于 这种特殊情况空对象 ),它可以正常工作:

select * from test where foo::text <> '{}'::text;
2020-07-27