sql - 如何查询空对象的 json 列?

查找某个 json 列包含空对象 {} 的所有行。这对于 JSON 数组是可能的,或者如果我正在寻找对象中的特定键。但我只想知道对象是否为空。似乎找不到可以执行此操作的运算符(operator)。

 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.

最佳答案

对于数据类型 json 没有等式(或不等式)运算符 作为一个整体,因为平等很难建立。考虑 jsonb 在 Postgres 9.4 或更高版本中,这是可能的。有关 dba.SE(最后一章)的相关答案中的更多详细信息:

  • How to remove known elements from a JSON[] array in PostgreSQL?

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

将表达式的两边都转换为 text允许 =<>运算符,但这通常不可靠,因为 same JSON 值有许多可能的文本表示。在 Postgres 9.4 或更高版本中,转换为 jsonb反而。 (或使用 jsonb 开头。)

然而,对于这种特殊情况(空对象)它工作得很好:

select * from test where foo::text <> '{}'::text;

https://stackoverflow.com/questions/24292575/

相关文章:

c# - asp.net asmx Web 服务返回 xml 而不是 json

java - JSON - 遍历 JSONArray

javascript - JSON 中空与空的约定是什么?

json - 在 shell 脚本中读取 JSON 数据

database - Fabric.js - 如何使用自定义属性在服务器上保存 Canvas

java - 在不知道 JSON 格式的情况下用 Java 解析 JSON

json - 将逻辑表示为 JSON 中的数据

c# - 复杂类型在 ApiController 参数中为空

c# - 为什么 DateTime.MinValue 不能在 UTC 之前的时区中序列化?

java - Gson 是否必须使用默认的无参数构造函数?