Oralce JSON_OBJECT_T使用

ORACLE JSON处理

  • 声明json
DECLARE
P_CLOB CLOB :=
'{  
   "age":123
}';
V_JSON_IN JSON_OBJECT_T := JSON_OBJECT_T.PARSE(P_CLOB);
V_AGE_ID NUMBER := V_JSON_IN.GET_NUMBER('age');

BEGIN	
    dbms_output.put_line(V_AGE_ID);
END;

  • 设置值
declare
    P_CLOB CLOB;
    -- 声明一个json对象
    V_JSON_OUT JSON_OBJECT_T := NEW JSON_OBJECT_T;
begin
    --为这个json对象赋值
    V_JSON_OUT.PUT('firstname', '王');
    -- 获取指定的key值
    P_CLOB := V_JSON_OUT.GET_CLOB('firstname');  
    P_CLOB := V_JSON_OUT.GET_STRING('firstname'); 
    -- 输出
    DBMS_OUTPUT.put_line(TO_CHAR(P_CLOB));
end;

JSON_ARRAY_T

DECLARE
	-- 声明字符串变量
	p_json_str VARCHAR2(500);
	--数组变量
	p_json_list JSON_ARRAY_T;
	-- json变量
	p_json JSON_OBJECT_T;
	p_name VARCHAR2(20);
	p_age number;
BEGIN
	p_json_str := '[
	{"name": "lisi", "age": 30},
	{"name":"zhangsan", "age": 20}
	]';
	-- 字符解析成json数组
	p_json_list := JSON_ARRAY_T.parse(p_json_str);
	-- 数组长度
	DBMS_OUTPUT.PUT_LINE(p_json_list.get_size);
	FOR i IN 0.. p_json_list.get_size - 1 LOOP
		p_json := JSON_OBJECT_T(p_json_list.get(0));
		
		p_name := p_json.get_string('name');
		
		p_age := p_json.get_number('age');
		
		dbms_output.put_line('name:'||p_name||';age:'||p_age);
	END LOOP;
	-- 添加数据
	p_json := new JSON_OBJECT_T;
	p_json.put('name', '王五');
	p_json.put('age', 23);
	p_json_list.append(p_json);
	dbms_output.put_line(p_json_list.to_string());
        -- 大文本
        dbms_output.put_line(p_json_list.to_clob());        
	DBMS_OUTPUT.PUT_LINE(JSON_OBJECT_T(p_json_list.get(0)).get_number('age'));
END;

JSON_OBJECT_T和JSON_ARRRAY_T

declare
	str varchar(4000) := '{"data": [{"cm_id":12}, {"cm_id":13}]}';   -- 参数
	returnJson JSON_OBJECT_T;  -- json 对象
	store JSON_OBJECT_T;  -- json对象
	pudList JSON_ARRAY_T:= new JSON_ARRAY_T;  -- 数组
begin
	-- 解析json对象
	returnJson := JSON_OBJECT_T.parse(str);
	-- 获取数组对象
	pudList := returnJson.get_array('data');
	-- 循环获取数组内的数据
	for i in 0 .. pudList.get_size - 1 loop
		-- 获取json对象
		store := TREAT(pudList.get(i) AS json_object_t);
		-- 取出获取的json对象key对应的值
		dbms_output.put_line(store.get_number('cm_id'));
	end loop;
end;

posted @ 2021-03-08 16:15  hziwei  阅读(1893)  评论(0编辑  收藏  举报