繁体   English   中英

Oracle 12c JSON TABLE解析错误处理

[英]Oracle 12c JSON TABLE parsing error handling

使用JSON_TABLE解析无效的 JSON 时是否可以处理错误? 例如下面的查询工作

SELECT *
FROM 
JSON_TABLE(
    '[{"productCode":"AD","serials":[{"id":"234242343","isPrimary":true}]},{"productCode":"BC","serials":[{"id":"23345345","isPrimary":true}]}]'
    , '$[*]'
    columns(
        productCode varchar2 PATH '$.productCode' NULL ON ERROR,
        serials varchar2 format JSON PATH '$.serials' NULL ON ERROR
    )
);

上面的output如下:

|PRODUCTCODE | SERIALS                              |
|---------------------------------------------------|
|AD          |[{"id":"234242343","isPrimary":true}] |
|BC          |[{"id":"23345345","isPrimary":true}]  |

在上面的例子中,输入 JSON 是有效的,但是,在我的例子中,不能保证它是从另一个日志表中获取的。

如果遇到无效的 JSON,我希望查询忽略。

简单的方法是将数据转移到具有检查约束的新表中,以检查源表中的数据是否符合JSON格式作为 Oracle 12c+ 用户。

如果格式为 false,则该行不会插入到该新表中,例如

CREATE TABLE tab_new (
  id      INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  jsdata  VARCHAR2(500),
  CONSTRAINT json_chk CHECK (jsdata IS JSON)
);

BEGIN
  FOR C IN ( SELECT jsdata FROM tab_old )
  LOOP
  BEGIN
     INSERT INTO tab_new(jsdata) VALUES(c.jsdata) ;
   EXCEPTION
     WHEN OTHERS THEN IF SQLCODE = -2290 THEN 
                       INSERT INTO tab_error(jsdata) VALUES(c.jsdata) ;
                      END IF;
  END;
  END LOOP;
  COMMIT;
END;
/

演示

您可以使用is json条件来过滤掉无效的 JSON:

create table t (
  what varchar2(20),
  c1   varchar2(500)
);

insert into t 
  values ( 'valid JSON', '[{"productCode":"AD","serials":[{"id":"234242343","isPrimary":true}]},{"productCode":"BC","serials":[{"id":"23345345","isPrimary":true}]}]' );
insert into t 
  values ( 'invalid JSON', '"productCode":"AD","serials":[{"id":"234242343","isPrimary":true}]},{"productCode":"BC","serials":[{"id":"23345345","isPrimary":true}]}]' );
commit;

select what from t
where  c1 is json;

WHAT         
valid JSON   

但这是不必要的: json_table已经忽略了无效文档!

SELECT what, j.*
FROM   t, JSON_TABLE(
    c1, '$[*]'
    columns(
      productCode varchar2 PATH '$.productCode' NULL ON ERROR,
      serials varchar2 format JSON PATH '$.serials' NULL ON ERROR
    )
) j;

WHAT          PRODUCTCODE    SERIALS                                 
valid JSON    AD             [{"id":"234242343","isPrimary":true}]    
valid JSON    BC             [{"id":"23345345","isPrimary":true}]  

您可以使用on error子句在无效的 JSON 上强制出错:

SELECT what, j.*
FROM   t, JSON_TABLE(
    c1, '$[*]'
    error on error
    columns (
      productCode varchar2 PATH '$.productCode' NULL ON ERROR,
      serials varchar2 format JSON PATH '$.serials' NULL ON ERROR
    )
) j;

ORA-40441: JSON syntax error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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