sql - 如何在 json 字段类型 postgresql 中查询空值?

我在 postgresql 中有一个 json 类型的字段。但是我无法选择特定字段为空的行:

代码:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
{"name2": "Zaphod", "occupation2": null} ]'  ) AS elem
where elem#>'{occupation2}' is null

这应该可以,但我收到此错误:

ERROR:  operator does not exist: json #> boolean
LINE 6: where elem#>'{occupation2}' is null

最佳答案

您可以使用 elem->'occupation2' 返回 json 类型的字符串 null 的事实,因此您的查询将是:

select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->'occupation2')::text = 'null'

{"name2": "Zaphod", "occupation2": null}

如果您想获取 JSON 中值为 null 或 key 不存在的所有元素,您可以这样做:

select
    *
from  json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ,
    {"name2": "Zaphod", "occupation2": null} ]'
) as elem
where (elem->>'occupation2') is null

{"name": "Toby", "occupation": "Software Engineer"}
{"name": "Zaphod", "occupation": "Galactic President"}
{"name2": "Zaphod", "occupation2": null}

https://stackoverflow.com/questions/19422640/

相关文章:

java - Jackson @JsonProperty(required=true) 不会抛出异常

sql - Postgresql 中的 `->>` 和 `->` 有什么区别?

json - 为什么 RestTemplate 不将响应表示绑定(bind)到 PagedResou

java - 如何在 Gson 序列化中保持字段顺序

javascript - D3.js:使用图像(在数据中指定文件名)作为轴上的刻度值

javascript - 如何使用 JSON.NET 通过 ASP.NET MVC 传递 JSON

python - 从文本文件中检索变量值的最佳方法?

java - Jackson - 反序列化 JSON 字符串 - TypeReference 与 T

javascript - 有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为

json - Scala 2.10 + Json 序列化和反序列化