Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Key Value as resultset from Oracle JSON column using JSON_TABLE

Tags:

json

oracle

I have googled aplenty, and can't seem to find a simple solution to my simple use case. I have a json column in an Oracle 12C database (actually a varchar with json constraint of course), and in that column I store a representation of a Map like this

{
"a":9.0847,
"b":859.947
}

In plsql I would like to return a result set of that looks like this

key val
a   9.0847
b   859.947

I have tinkered with seemingly infinite variations of this below, and all the examples are too contrived for my use case.

select b.* from mytable a,json_table(myJsonCol,'$'
columns ( value varchar2(500) path '$.myjsonkey')) b

but this only returns a list of values, without the corresponding keys. The json data is ALWAYS string-double key vals.

thanks

EDIT To add a bit more context, i use json_each in postgres to do this now, and i'm looking for a similar method in Oracle.

like image 902
Mark Giaconia Avatar asked Nov 04 '16 13:11

Mark Giaconia


People also ask

What is JSON_TABLE?

JSON_TABLE creates a relational view of JSON data. It maps the result of a JSON data evaluation into relational rows and columns. You can query the result returned by the function as a virtual relational table using SQL.

How parse JSON in PL SQL?

Now we can use following SQL to parse Nested JSON data along with JSON Array in Oracle Database by using JSON_TABLE function. ngarg> SELECT 2 DEPTNO, DNAME, EMPNO, ENAME, JOB, SAL 3 FROM 4 DEPT_JSON D, 5 JSON_TABLE 6 ( 7 D. JSON_VALUE, '$' COLUMNS 8 ( 9 DEPTNO NUMBER(4) PATH '$.

Which of the following statements is used to view the JSON content of the rendered chart?

The JSON_TABLE operator is used in the FROM clause of a SQL statement. It enables the creation of an inline relational view of JSON content.


1 Answers

Try this:

declare
  jo JSON_OBJECT_T;
  i  NUMBER;
  keys JSON_KEY_LIST;
  CURSOR c_json IS
     SELECT myJsonCol FROM mytable;
begin
  FOR rec IN c_json
  LOOP
     jo := JSON_OBJECT_T.parse(rec.myJsonCol);
     keys := jo.get_keys;
     dbms_output.put_line('KEY VAL');
     FOR i in 1..keys.COUNT
     LOOP
        dbms_output.put_line(keys(i) || ' ' || jo.get_Number(keys(i)));
     END LOOP;
   END LOOP;
END;
/
like image 69
Saxon Avatar answered Oct 05 '22 01:10

Saxon