我正在尝试从Oracle数据库中的嵌套JSON中提取键和值对。 JSON在我的数据库中保存为CLOB。
我无法从查询中获取密钥名称:
select key_v, var_name, sub_q
from sampletable,
json_table (sample_json , '$'
columns (key_v varchar2(36) path '$."result"."exportColumnMap"',
nested path '$."result"."exportColumnMap".*'
columns (var_name varchar2(24) path '$."question"',
sub_q varchar2(36) path '$."choice"'
)))
where var_name is not null;
理想情况下,select语句中的结果表最终为
KEY_1, ANSWER1, QUESTION1
KEY_2, ANSWER2, QUESTION2
KEY_3, ANSWER3, QUESTION3
sample_json:
{"result":
"exportColumnMap": {
"KEY_1": {
"choice": "ANSWER1",
"question": "QUESTION1"
},
"KEY_2": {
"choice": "ANSWER2",
"question": "QUESTION2"
},
"KEY_3": {
"choice": "ANSWER3",
"question": "QUESTION3"
}}}
答案 0 :(得分:0)
所以,有几件事情。首先,您的JSON无效。顶级布局为“{KEY:KEY:{VALUE}}”,当它应为“{KEY:{KEY:{VALUE}}}”时,如下所示:
{"result":
{"exportColumnMap": {
"KEY_1": {
"choice": "ANSWER1",
"question": "QUESTION1"
},
"KEY_2": {
"choice": "ANSWER2",
"question": "QUESTION2"
},
"KEY_3": {
"choice": "ANSWER3",
"question": "QUESTION3"
}}}}
其次,您的查询看起来很不错,但遗憾的是我并不知道检索JSON密钥名称的简单方法。您的key_v
列会检索KEY_1,KEY2等的值,它们看起来像{"choice": "ANSWER1",...}
,而不是“KEY_1”的键名。使用像这样的常规列会更容易,如果你真的需要列值在它们前面有“KEY_”,那么稍后粘贴它。或者更改JSON的结构以将要检索的所有值存储为值而不是键名。
select key_v, var_name, sub_q
from sampletable,
json_table (sample_json , '$'
columns (key_v FOR ORDINALITY,
nested path '$."result"."exportColumnMap".*'
columns (var_name varchar2(24) path '$."question"',
sub_q varchar2(36) path '$."choice"'
)))
where var_name is not null;
此输出如下:
1, ANSWER1, QUESTION1
2, ANSWER2, QUESTION2
3, ANSWER3, QUESTION3