col name for a30 col sex for a30 select a.id,a.data.name,a.data.sex from ( select id, treat(document as json) as data from json_test) a order by 2;
ID NAME SEX -------------------------------- ------------------------------ ------------------------------ BED184B8FC52F039E055FBD2D67647F4 lei male BED184B8FC51F039E055FBD2D67647F4 ting female BED184B8FC50F039E055FBD2D67647F4 xb male
使用Treat AS JSON和WITH从句
1 2 3 4 5 6 7 8 9 10 11
col name for a30 col sex for a30 with t as (select id, treat(document as json) as data from json_test) select a.id, a.data.name, a.data.sex from t a order by 2;
ID NAME SEX -------------------------------- ------------------------------ ------------------------------ BED184B8FC52F039E055FBD2D67647F4 lei male BED184B8FC51F039E055FBD2D67647F4 ting female BED184B8FC50F039E055FBD2D67647F4 xb male
使用视图
1 2 3 4 5 6 7 8 9 10 11 12 13
create or replace view v_json as select id, treat(document as json) as data from json_test;
select a.id,a.data.name,a.data.sex from v_json a order by 2;
ID NAME SEX -------------------------------- ------------------------------ ------------------------------ BED184B8FC52F039E055FBD2D67647F4 lei male BED184B8FC51F039E055FBD2D67647F4 ting female BED184B8FC50F039E055FBD2D67647F4 xb male
Treat AS JSON错误处理
在使用treat as json语法时,插入的数据并没有进行json格式的约束,就会导致列中存在一些并不是JSON格式的数据,而treat as json也不会去做校验。
1 2 3 4 5 6 7 8 9 10 11 12 13
insert into json_test values (SYS_GUID(), 'name: xb, sex: male'); commit;
col json_data for a80 select id,treat(document as json) json_data from json_test;
col name for a30 col sex for a30 select a.id,a.data.name,a.data.sex from ( select id, treat(document as json) as data from json_test) a order by 2;
ID NAME SEX -------------------------------- ------------------------------ ------------------------------ BED184B8FC52F039E055FBD2D67647F4 lei male BED184B8FC51F039E055FBD2D67647F4 ting female BED184B8FC50F039E055FBD2D67647F4 xb male BED184B8FC56F039E055FBD2D67647F4
可以通过加IS JSON的条件来过滤掉这些NULL数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14
col name for a30 col sex for a30 select a.id,a.data.name,a.data.sex from ( select id, treat(document as json) as data from json_test) a where a.data is json order by 2;
ID NAME SEX -------------------------------- ------------------------------ ------------------------------ BED184B8FC52F039E055FBD2D67647F4 lei male BED184B8FC51F039E055FBD2D67647F4 ting female BED184B8FC50F039E055FBD2D67647F4 xb male