我在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
发布于 2013-10-17 20:35:23
您可以利用 elem->'occupation2' 返回 json 类型的字符串 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}
发布于 2016-01-28 22:56:35
如果您要在json-blob中搜索空值,则可能需要考虑使用Postgres9.4中引入的函数 json_typeof(json) :
json_typeof(json)
INSERT INTO table VALUES ('{ "value": "some", "object": {"int": 1, "nullValue": null}}'); SELECT * FROM table WHERE json_typeof(json->'object'->'nullValue') = 'null';
这将导致您找到NULL值的条目。
希望这能有所帮助!
参考: http://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE
发布于 2017-07-11 07:22:24
来自@roman-pekar和@mraxus的答案很有帮助,但我并不满意,因为我没有能力清楚地区分未定义和空...所以,我想出了:
CREATE OR REPLACE FUNCTION isnull (element json) RETURNS boolean AS $$