简体   繁体   中英

How to convert JSON format oracle table row values into multiple relational COLUMNS?

I have a oracle table that has been loaded by MQ and one of the table column has values with JSON format data.I need to convert those JSON format data into relational row format. I am wondering if there is any SQL in oracle with/without creating temp tables to convert those JSON format data into relational column values?

Select JSON_MG from test_1;

JSON_MG
{
  "type": "testeevnet",
  "version": "test-1.0",
  "testsource": "1.0.0",
  "timestamp": "2019-02-14T20:45:18.4422201+00:00",
  "test_ID": 11,
  "tag": "22",
  "PNAME": "test/test_n",
  "ticket": "WT9999",
  "ticketStatus": "active",
  "tickets": [
    {
      "ticket": "convert",
      "code": "PA",
      "date": "2019-03-31"
    }
    }
  ]
}

-- Expected result all the JSON elements as columns

json_table is what you're looking for. This can do JSON -> relational conversion.

Just list out the paths to the elements you want to extract & their data type:

with jdata as (
  select '{
  "type": "testeevnet",
  "version": "test-1.0",
  "testsource": "1.0.0",
  "timestamp": "2019-02-14T20:45:18.4422201+00:00",
  "test_ID": 11,
  "tag": "22",
  "PNAME": "test/test_n",
  "ticket": "WT9999",
  "ticketStatus": "active",
  "tickets": [
    {
      "ticket": "convert",
      "code": "PA",
      "date": "2019-03-31"
    }
  ]
}' doc
  from dual
)
  select t.* 
  from   jdata, json_table (
    doc, '$'
    columns (
      type    varchar2 path '$.type',
      version varchar2 path '$.version',
      nested  path '$.tickets[*]' 
      columns (
        ticket varchar2 path '$.ticket'
      )
    )
  ) t;

TYPE         VERSION    TICKET    
testeevnet   test-1.0   convert   

The nested path splits out the array elements into rows. So as you add more objects in your tickets array, they become rows:

with jdata as (
  select '{
  "type": "testeevnet",
  "version": "test-1.0",
  "testsource": "1.0.0",
  "timestamp": "2019-02-14T20:45:18.4422201+00:00",
  "test_ID": 11,
  "tag": "22",
  "PNAME": "test/test_n",
  "ticket": "WT9999",
  "ticketStatus": "active",
  "tickets": [
    {
      "ticket": "convert",
      "code": "PA",
      "date": "2019-03-31"
    },
    {
      "ticket": "convert2",
      "code": "PA",
      "date": "2019-03-31"
    }
  ]
}' doc
  from dual
)
  select t.* 
  from   jdata, json_table (
    doc, '$'
    columns (
      type    varchar2 path '$.type',
      version varchar2 path '$.version',
      nested  path '$.tickets[*]' 
      columns (
        ticket varchar2 path '$.ticket'
      )
    )
  ) t;

TYPE         VERSION    TICKET     
testeevnet   test-1.0   convert     
testeevnet   test-1.0   convert2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM