1

JSON :

{
    "first": {
         "JAN": {
                "ID": "1",
                "Name": "Jim"
         }
    },
    "second": {
         "FEB": {
                "ID": "2",
                "Name": "Jack"
         }
    },
    "Idname" : "2",
    "Date" : "01/28/2014",
    "State" : "1"
}

I need to convert the JSON into a VIEW so that I can access the JSON fields as COLUMNS using a SELECT statement. I am using Oracle 11g Database.

The expected output for the following select query :

Select JAN_ID, JAN_NAME from <view name>;

gives the result :

1     Jim
0

1 Answer 1

1

JSON functions are defined for Database Oracle12c+ version. APEX_JSON package with release 5.0+ should be installed for the previous releases. Whenever installation complete, then the following code might be used as a workaround in order to extract the desired values :

DECLARE
   v_json VARCHAR2(32767); 
   v_mon1 OWA.VC_ARR;
   v_mon2 OWA.VC_ARR;
BEGIN
   SELECT *
     INTO v_json
     FROM j;  -- your JSON value is inserted into this table         
              -- there's no WHERE clause assuming only one row is to be inserted
   APEX_JSON.PARSE(v_json);
   FOR i IN 1..2
   LOOP
     v_mon1(i) := TO_CHAR(TO_DATE(i, 'j'),'jspth');
     v_mon2(i) := TO_CHAR(TO_DATE(i, 'mm'),'MON');

     DBMS_OUTPUT.PUT_LINE(APEX_JSON.GET_VARCHAR2(v_mon1(i)||'.'||v_mon2(i)||'.ID')||'  '||
                          APEX_JSON.GET_VARCHAR2(v_mon1(i)||'.'||v_mon2(i)||'.Name'));
   END LOOP;   
END;
/

If you need to create a view, then you convert the existing data to XMLTYPE, and then XMLTABLE function the extract the columns as

CREATE OR REPLACE VIEW v_people AS
WITH t AS
(
SELECT APEX_JSON.TO_XMLTYPE(jsdata) AS xml_data
  FROM j
), t2 AS
(  
SELECT xt1.*, xt2.*
  FROM t
 CROSS JOIN
       XMLTABLE('/json/first'
                PASSING xml_data
                COLUMNS 
                  ID1   INT  PATH 'JAN/ID',
                  Name1 VARCHAR2(100) PATH 'JAN/Name'
               ) xt1
 CROSS JOIN
       XMLTABLE('/json/second'
                PASSING xml_data
                COLUMNS 
                  ID2   INT  PATH 'FEB/ID',
                  Name2 VARCHAR2(100) PATH 'FEB/Name'
               ) xt2               
)
SELECT ID1 AS ID, Name1 AS Name FROM t2
UNION ALL
SELECT ID2, Name2 FROM t2  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.