Rashmik
Rashmik

Reputation: 117

Parsing JSON data from CLOB field using PL/SQL

I have data in the following format stored in a CLOB field of a table-

{
  "key" : "PRODUCT_NAME",
  "value" : "Myproduct"
}, {
  "key" : "PRODUCT_TYPE",
  "value" : "Electronics"
}, {
  "key" : "PRODUCT_PRICE",
  "value" : "123456789.1"
}

I want to store them in a table which will be having columns PRODUCT_NAME,PRODUCT_TYPE,PRODUCT_PRICE and they will be stored as

PRODUCT_NAME PRODUCT_TYPE PRODUCT_PRICE
MyProduct    Electronics  123456789.1

I want to perform these using Pl/SQL. Any pointers here?

Upvotes: 5

Views: 20184

Answers (2)

Kaushik Nayak
Kaushik Nayak

Reputation: 31716

The CLOB field you are using is not a valid JSON, so you can't use the JSON functions directly. You need to go through the JSON documentation and understand how a json should be stored in a database table in order to make it easier to use them. One solution for you would be to parse the individual jsons first and then apply JSON_OBJECT on each json. Furthermore, you would need a PIVOT or a MAX(CASE) block to convert the rows into columns. This query works in Oracle 12c and above.

Sample data

CREATE TABLE t AS 
  SELECT 1   AS id, 
         To_clob('{   "key" : "PRODUCT_NAME",   "value" : "Myproduct" }, {   "key" : "PRODUCT_TYPE",   "value" : "Electronics" }, {   "key" : "PRODUCT_PRICE",   "value" : "123456789.1" }') AS j 
  FROM   dual 
  UNION ALL 
  SELECT 2, 
         To_clob('{   "key" : "PRODUCT_NAME",   "value" : "Myproduct2" }, {   "key" : "PRODUCT_TYPE",   "value" : "Chemical" }, {   "key" : "PRODUCT_PRICE",   "value" : "25637.1" }') 
  FROM   dual; 

Query

WITH jdt AS 
( 
       SELECT id, 
              JSON_VALUE(jsons,'$.key')   AS k,  -- gets the "key"
              JSON_VALUE(jsons,'$.value') AS v   -- gets the "value"
       FROM   ( 
                     SELECT id, 
                            REGEXP_SUBSTR(j,'(.*?)\}(,|$)',1,LEVEL,'n',1) 
                                   || '}' AS jsons --split the clob field into individual jsons
                     FROM   t 
                            CONNECT BY PRIOR id = id 
                     AND    PRIOR SYS_GUID() IS NOT NULL 
                     AND    LEVEL <= REGEXP_COUNT(j,'\}(,|$)') ) ) 
SELECT * 
FROM   jdt pivot ( max ( v ) FOR k IN ( 'PRODUCT_NAME', 
                                       'PRODUCT_TYPE', 
                                       'PRODUCT_PRICE' ) );

 ID PRODUCT_NAME PRODUCT_TYPE   PRODUCT_PRICE
 1  Myproduct    Electronics    123456789.1
 2  Myproduct2   Chemical       25637.1

Upvotes: 3

TheName
TheName

Reputation: 733

Try to use PL/JSON it has various of functions and procedures for JSON parsing https://pljson.github.io/pljson/

Upvotes: 0

Related Questions