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

时间:2013-10-17 09:16:44

标签: 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

4 个答案:

答案 0 :(得分:50)

您可以使用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}

如果要获取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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分: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

它很短,如果json值未定义(返回null),也会给我一个信号。也许这对这个问题很有用。

答案 3 :(得分: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