从Oracle JSON对象中删除属性

时间:2019-05-27 19:54:41

标签: json oracle

用例: 应用程序需要基于业务规则的属性子集

示例: 有些学生不需要输入家庭住址

数据库:Oracle

拟议实施: 构建包含所有可能的命名对的json对象,然后有选择地删除特定的命名对

问题: 希望使用本机oracle函数删除指定的命名对。 例如json_object.remove_attribute('home_address'); 但是,Oracle似乎没有提供任何此类方法。

解决方法:将json_object转换为VARCHAR2字符串,然后结合使用INSTR和REPLACE删除命名对。

说明性代码:

DECLARE
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
       ,'s_surname'                     value s.s_surname
       ,'s_forename_1'                  value s.s_forename_1
       ,'s_home_address_1'              value s.s_home_address_1  
  RETURNING VARCHAR2 ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN
  FOR x IN cur_student_json (p_s_ref) LOOP
    vs_student_json:=x.student_json;  
    EXIT;
  END LOOP;  

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type  
  FOR x IN cur_json_inorout(vs_student_type) LOOP   
     -- Remove element from the json
     vs_student_json:=json_remove(vs_student_json,x.attribute);
  END LOOP;
END;
/

问题: 必须有一个优雅的方法来达到要求

1 个答案:

答案 0 :(得分:0)

根据RTFM分类。需要Oracle 12.2

DECLARE

  -- Declare an object of type JSON_OBJECT_T
  l_obj JSON_OBJECT_T;

  -- Declare cursor to build json object
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
      ,'s_surname'                     value s.s_surname
      ,'s_forename_1'                  value s.s_forename_1
      ,'s_home_address_1'              value s.s_home_address_1 
    ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN

  -- Initialise object
  l_obj := JSON_OBJECT_T();

  -- Populate the object
  FOR x IN cur_student_json (p_s_ref) LOOP
    l_obj:=JSON_OBJECT_T.parse(x.student_json); 
    EXIT;
  END LOOP;  

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type  
  FOR x IN cur_json_inorout(vs_student_type) LOOP   
    -- Remove element from the json
    l_obj.remove(x.attribute);
  END LOOP;

  -- Display modified object
  dbms_output.put_line(l_obj.stringify);
END;
/