How to update a part of JSON string in Oracle 12c?

主宰稳场 提交于 2019-12-11 07:33:05

问题


I've a table in my oracle DB as below.

CREATE TABLE my_table(
  id    RAW(16) NOT NULL,
  data  CLOB,
  CONSTRAINT my_table_pk PRIMARY KEY (id),
  CONSTRAINT my_table_json_chk CHECK (data IS JSON)
);


INSERT INTO my_table (id, data)
VALUES (SYS_GUID(),
        '{
          "FirstName"      : "aa",
          "LastName"       : "bb",          
          "Address"        : {
                              "Street"   : "99 My Street",
                              "City"     : "My City",
                              "Country"  : "UK",
                              "Postcode" : "A12 34B"
                             }');

Now I know, I can fetch value of a specific property like address of the JSON string using $.

Similarly, can I update Street property of the JSON string without providing the entire JSON structure in my update query?

Please help me on this.


回答1:


This is supported via PL/SQL in 12.2.0.1.0. New PL/SQL objects enable fine grained manipulation of JSON content

  • JSON_OBJECT_T: for working with JSON objects
  • JSON_ARRAY_T: for working with JSON Arrays

JSON_OBJECT_T and JSON_ARRAY_T are subtypes of JSON_ELEMENT_T

These objects provide a set of methods for manipulating JSON similar to GSON.

enter code here 
 WITH FUNCTION updateTax(JSON_DOC in VARCHAR2 ) RETURN VARCHAR2 
 IS
    jo JSON_OBJECT_T;  
    price NUMBER;  
    taxRate NUMBER; 
 BEGIN
    jo := JSON_OBJECT_T(JSON_DOC);     
    taxRate := jo.get_Number('taxRate');   
    price := jo.get_Number('total');   
    jo.put('totalIncludingTax', price * (1+taxRate));  
    RETURN jo.to_string(); 
 END; 
 ORDERS as (
    select '{"taxRate":0.175,"total":10.00}' JSON_DOCUMENT       
      from dual 
 ) 
 select JSON_DOCUMENT, updateTax(JSON_DOCUMENT)
  from ORDERS; 

JSON_DOCUMENT                   UPDATETAX(JSON_DOCUMENT)
------------------------------- --------------------------------------------------------
{"taxRate":0.175,"total":10.00} {"taxRate":0.175,"total":10.00,"totalIncludingTax":11.75} 

https://docs.oracle.com/database/122/ADJSN/using-PLSQL-object-types-for-JSON.htm#ADJSN-GUID-F0561593-D0B9-44EA-9C8C-ACB6AA9474EE



来源:https://stackoverflow.com/questions/41768597/how-to-update-a-part-of-json-string-in-oracle-12c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!