json - 从 CLOB 数据类型列生成 Oracle JSON
问题描述
要求是从 clob 数据类型列生成 JSON。环境版本 Oracle 12.2
我有一个带有字段 id(数字数据类型)和详细信息(clob 类型)的表,如下所示
ID - details
100 - 134332:10.0, 1481422:1.976, 1483734:1.688, 2835036:1.371
101 - 134331:0.742, 319892:0.734, 1558987:0.7, 2132090:0.697
例如输出:
{
"pId":100,
"cid":[
{
"cId":134332,
"wt":"10.0"
},
{
"cId":1481422,
"wt":"1.976"
},
{
"cId":1483734,
"wt":"1.688"
},
{
"cId":2835036,
"wt":"1.371"
}
]
}
请帮助使用 oracle SQL 查询以生成输出。
解决方案
下面我设置了一个表,其中包含一些输入行进行测试;然后我展示了一种解决问题的方法,以及该查询的输出。我没有尝试编写最有效(最快)的查询;相反,我希望这将向您展示如何做到这一点。然后,如果速度是一个问题,你可以解决这个问题。(在这种情况下,最好先重新考虑输入,这会破坏第一范式。)
我添加了几个输入行进行测试,看看null
是如何处理的。您可以决定这是否是所需的处理方式。(null
有可能您的数据中不可能存在 - 在这种情况下,您应该在提问时这么说。)
设置测试表:
create table input_tbl (id number primary key, details clob);
insert into input_tbl (id, details) values
(100, to_clob('134332:10.0, 1481422:1.976, 1483734:1.688, 2835036:1.371'));
insert into input_tbl (id, details) values
(101, '134331:0.742, 319892:0.734, 1558987:0.7, 2132090:0.697');
insert into input_tbl (id, details) values
(102, null);
insert into input_tbl (id, details) values
(103, '2332042: ');
commit;
询问:
with
tokenized (pid, ord, cid, wt) as (
select i.id, q.ord, q.cid, q.wt
from input_tbl i cross apply
(
select level as ord,
regexp_substr(details, '(, |^)([^:]+):', 1, level, null, 2)
as cid,
regexp_substr(details, ':([^,]*)', 1, level, null, 1) as wt
from dual
connect by level <= regexp_count(details, ':')
) q
)
, arrayed (pid, json_arr) as (
select pid, json_arrayagg(json_object(key 'cId' value to_number(trim(cid)),
key 'wt' value to_number(trim(wt)))
)
from tokenized
group by pid
)
select pid, json_object(key 'pId' value pid, key 'cid' value json_arr) as json
from arrayed
;
输出:
PID JSON
---- -----------------------------------------------------------------------------------------------------------------------------
100 {"pId":100,"cid":[{"cId":134332,"wt":10},{"cId":2835036,"wt":1.371},{"cId":1483734,"wt":1.688},{"cId":1481422,"wt":1.976}]}
101 {"pId":101,"cid":[{"cId":134331,"wt":0.742},{"cId":2132090,"wt":0.697},{"cId":1558987,"wt":0.7},{"cId":319892,"wt":0.734}]}
102 {"pId":102,"cid":[{"cId":null,"wt":null}]}
103 {"pId":103,"cid":[{"cId":2332042,"wt":null}]}
推荐阅读
- sql - 从视图中提取的日期过滤不起作用
- javascript - Google auth - 允许用户切换帐户
- jquery - Select2 组选择。值 当鼠标悬停在值上时自动跳到顶部
- php - 列出所有项目并突出显示给定类别中的项目
- django - Django DJANGO_SETTINGS_MODULE 在 Cookiecutter 中变回 'config.settings.local'
- docker - 当我在 Dockerfile 中使用 root 用户时构建图像报告“需要是 root”
- ios - 领域:- 由于未捕获的异常“RLMException”而终止应用程序?
- css - 视频应触及盒子的顶部和底部
- firebase - Firestore 安全规则 - 获取集合时 {wildcard} 既不为空也不为空
- c - 将 2D 数组转换为 3D?