如何在ORACLE中解析JSON数据

oknwwptz  于 2023-01-12  发布在  Oracle
关注(0)|答案(2)|浏览(452)

一个表的HUGECLOB列有JSON数据,我想解析一下,怎么解析呢?

{"errors":{"destination_country_id":["can not be blank"],"dispatch_country_id":["can not be blank"],"vehicle_id":["can not be blank"],"trailer_id":["can not be blank"]}}

我试过这个;

SELECT t.*
    FROM table,
         JSON_TABLE(_hugeclob_data, '$'
              COLUMNS (destination_country_id  VARCHAR2(50 CHAR) PATH '$.destination_country_id',
                       dispatch_country_id     VARCHAR2(50 CHAR) PATH '$.dispatch_country_id',
                       vehicle_id              VARCHAR2(50 CHAR) PATH '$.vehicle_id',
                       trailer_id              VARCHAR2(50 CHAR) PATH '$.trailer_id'                  
                      )
                  ) t;
nkkqxpd9

nkkqxpd91#

如果字段是标量,但定义为数组(如示例中所示),请执行以下操作

SELECT t.*
    FROM table t1,
         JSON_TABLE(_hugeclob_data format json, '$.errors'
              COLUMNS (destination_country_id  VARCHAR2(50 CHAR) PATH '$.destination_country_id[*]',
                       dispatch_country_id     VARCHAR2(50 CHAR) PATH '$.dispatch_country_id[*]',
                       vehicle_id              VARCHAR2(50 CHAR) PATH '$.vehicle_id[*]',
                       trailer_id              VARCHAR2(50 CHAR) PATH '$.trailer_id[*]'                  
                      )
                  ) t;

但如果它们实际上是数组,则需要使用“nested path”声明来展开数组

mccptt67

mccptt672#

这里有一个选项,它取每个数组的第一个元素:

create table test_table (
    id                             number generated by default on null as identity 
                                   constraint test_table_id_pk primary key,
    clob_data                      clob  CHECK (clob_data IS JSON)
)
;

INSERT INTO test_table(clob_data) VALUES
(
'{
  "errors": {
    "destination_country_id": [
      "can not be blank"
    ],
    "dispatch_country_id": [
      "can not be blank"
    ],
    "vehicle_id": [
      "can not be blank"
    ],
    "trailer_id": [
      "can not be blank"
    ]
  }
}');

SELECT t.*
FROM test_table,
JSON_TABLE(clob_data, '$.errors'
COLUMNS (row_number FOR ORDINALITY,
         destination_country_id VARCHAR2(4000) PATH '$.destination_country_id[0]',
         dispatch_country_id VARCHAR2(4000) PATH '$.dispatch_country_id[0]',
         vehicle_id VARCHAR2(4000) PATH '$.vehicle_id[0]',
         trailer_id VARCHAR2(4000) PATH '$.trailer_id[0]'
        ))
AS t;

ROW_NUMBER DESTINATION_COUNTRY_ DISPATCH_COUNTRY_ID  VEHICLE_ID           TRAILER_ID          
---------- -------------------- -------------------- -------------------- --------------------
         1 can not be blank     can not be blank     can not be blank     can not be blank

相关问题