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

Ale*_*u R 40 sql postgresql json

我在postgresql中有一个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}' is null
Run Code Online (Sandbox Code Playgroud)

这应该工作,但我收到此错误:

ERROR:  operator does not exist: json #> boolean
LINE 6: where elem#>'{occupation2}' is null
Run Code Online (Sandbox Code Playgroud)

Rom*_*kar 54

你可以使用elem->'occupation2'返回null类型字符串的事实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')::text = 'null'

{"name2": "Zaphod", "occupation2": null}
Run Code Online (Sandbox Code Playgroud)

如果你想获得值为nullJSON或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}
Run Code Online (Sandbox Code Playgroud)

  • 这在 plpgsql 中也对我有用。在检查它是否为空之前,我必须将 json 提取物放在括号中。 (2认同)
  • 也许关联性规则对其他人来说是显而易见的(也许这也是 @Imraan 所说的),但在转换为文本之前我没有意识到括号的重要性。意思是, `elem->'ocupation2'::text` 不起作用,但(如您所见), `(elem->'ocupation2')::text` 起作用。 (2认同)

mra*_*xus 8

如果要在json-blob中搜索空值,可能需要考虑使用json_typeof(json)Postgres 9.4中引入的函数:

INSERT INTO table
  VALUES ('{ "value": "some", "object": {"int": 1, "nullValue": null}}');

SELECT * FROM table
  WHERE json_typeof(json->'object'->'nullValue') = 'null';
Run Code Online (Sandbox Code Playgroud)

这将导致您找到空值的条目.

希望这可以帮助!

参考:http: //www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE