56

我在 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
4

4 回答 4

70

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}

如果要获取值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') is null

{"name": "Toby", "occupation": "Software Engineer"}
{"name": "Zaphod", "occupation": "Galactic President"}
{"name2": "Zaphod", "occupation2": null}
于 2013-10-17T12:35:22.707 回答
13

如果您在 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';

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

希望这可以帮助!

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

于 2016-01-28T14:56:34.527 回答
1

为此使用 dbeaver 编辑器,它在那里工作。

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
于 2020-08-21T11:40:07.400 回答
1

@roman-pekar 和 @mraxus 的回答很有帮助,但我对无法清楚地区分 undefined 和 null 感到不满意......所以,我想出了:

CREATE OR REPLACE FUNCTION isnull (element json)
RETURNS boolean AS $$
  SELECT (element IS NOT NULL) AND (element::text = 'null');
$$ LANGUAGE SQL IMMUTABLE STRICT;

select isnull('{"test":null}'::json->'test'); -- returns t
select isnull('{"test":"notnull"}'::json->'test'); -- returns f
select isnull('{"toot":"testundefined"}'::json->'test'); -- returns null

@a_horse_with_no_name 还指出了?postgresql 9.4 版中引入的附加 jsonb 运算符:

SELECT '{"a":1, "b":2}'::jsonb ? 'b'
于 2017-07-10T23:22:23.613 回答