[英]extract items from json array by condition in oracle
我正在学习 Oracle 的 json 特性的一些基础知识,但对如何执行以下操作感到困惑。
我在 clob 中有一个以数组为根的 json,例如。
[{"str":"foo","num":1},{"str":"bar","num":2},{"str":"foobar","num":3}]
我想从数组中提取特定项目,为数组对象定义各种条件,例如。 当我以某种方式指定“where num:= 2”条件时,结果应该是这个字符串:
[{"str":"foo","num":1},{"str":"foobar","num":3}]
Oracle 的 bultin json 函数如何完成? 如何指定任意条件?
重要的是,不一定所有的键(属性名称)都只知道条件所代表的键,因此不能像 json_table 所要求的那样枚举所有键。
换句话说,我正在寻找一种方法来使用 json 做与编写相同的事情
select * from jsontext where num!=2
对于一个真正的表。
唯一能想到的就是解析JSON,过滤数据,再生成JSON。
JSON 格式的支持是在 12.1 中首次引入的,因此使用 12.1 或更新版本至关重要。 这是获取版本的方法
select version from v$instance;
如果您使用的是 12.1(仅此版本,不是更新版本),那么这可能会有所帮助
select '[' || listagg('{"str": "' || jt.str || '", "num": ' || jt.num || '}', ',') within group(order by 1) || ']'
from json_table('[{"str":"foo","num":1},{"str":"bar","num":2},{"str":"foobar","num":3}]',
'$[*]' columns(str path '$.str', num path '$.num')) jt
where num != 2;
在 12.2 中引入了另一个功能,可以稍微减少代码量。 json_object 函数将列组装成一个 json 对象,而 json_arrayagg 是将数据聚合到一个 JSON 数组。 所以在 12.2 和更新版本上,您的代码可能如下所示
select json_arrayagg(json_object('str' value str, 'num' value jt.num))
from json_table('[{"str":"foo","num":1},{"str":"bar","num":2},{"str":"foobar","num":3}]',
'$[*]' columns(str path '$.str', num path '$.num')) jt
where num != 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.