如何将JSON格式的oracle表行值转换为多个关系列?

时间:2019-06-06 19:35:59

标签: sql json oracle

我有一个由MQ加载的oracle表,其中一个表列具有JSON格式数据的值。我需要将这些JSON格式数据转换为关系行格式。我想知道oracle中是否有任何SQL创建/不创建临时表来将这些JSON格式的数据转换为关系列值?

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"
    }
    }
  ]
}

-预期结果将所有JSON元素作为列

1 个答案:

答案 0 :(得分:0)

json_table是您要寻找的。这可以执行JSON->关系转换。

只需列出要提取的元素的路径及其数据类型:

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   

nested path将数组元素拆分为行。因此,当您在票证数组中添加更多对象时,它们将成为行:

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