我有一个大型数据库,其中包含用 JSON 编写的分析数据。
我想过滤掉数据不正确的行:
- 无效的 JSON(有些行有类似的东西:
'{"hello": "world'
- 一些属性不是数组,所以它需要
'{"products": [1,2,3]}'
并且会省略'{"products": 1} '
我想做这样的事情:
select *
from analytics
where (is_correct_json(json::json))
and (is_array(json::json->>'products'))
我怎样才能做到这一点?
最佳答案
这是另一个很好的例子,为什么从一开始就选择合适的数据类型对以后有帮助 ;)
没有用于检查给定文本是否为有效 JSON 的内置函数。但是,您可以编写自己的:
create or replace function is_valid_json(p_json text)
returns boolean
as
$$
begin
return (p_json::json is not null);
exception
when others then
return false;
end;
$$
language plpgsql
immutable;
注意:由于异常处理,这不会很快。如果您对许多无效值调用它,这将大大降低您的选择速度。
但是 '{"products": 1}'
和 '{"products": [1,2,3]}'
都是有效的 JSON 文档。前者无效的事实是基于您的应用程序逻辑,而不是 JSON 语法。
验证您是否需要一个类似的函数,在调用 json_array_length()
时捕获错误
create or replace function is_valid_json_array(p_json text, p_element text)
returns boolean
as
$$
begin
return json_array_length( p_json::json -> p_element) >= 0;
exception
when others then
return false;
end;
$$
language plpgsql
immutable;
关于json - 如何验证字符串是 PostgreSQL 中的有效 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30187554/