首页 > 解决方案 > plsql 代码在不使用第三方库的情况下解析 JSON

问题描述

JSON 需要仅使用 PL/SQL 代码(如正则表达式)进行解析,以从中获取sentimentconfidence

类似的东西

[
   {
      "sentiment":"negative",
      "confidence":0.6211975044276729
   },
   {
      "sentiment":"neutral",
      "confidence":0.3510681601407111
   },
   {
      "sentiment":"positive",
      "confidence":0.027734335431616075
   }
]

上面的 JSON 需要被解析才能从中获取sentimentconfidence取值

标签: jsonoracleplsql

解决方案


JSON_TABLE函数从 Oracle Database 12c 第 1 版 (12.1.0.2) 开始可用

SET NUMWIDTH 20 --Use this if SQL*Plus/ SQL developer truncates digits.

--test data
WITH t ( json_col ) AS ( SELECT '[
   {
      "sentiment":"negative",
      "confidence":0.6211975044276729
   },
   {
      "sentiment":"neutral",
      "confidence":0.3510681601407111
   },
   {
      "sentiment":"positive",
      "confidence":0.027734335431616075
   }
]'
  FROM dual
) --test data ends
SELECT j.*
FROM t
CROSS JOIN
     JSON_TABLE ( json_col,'$[*]'
          COLUMNS (
               sentiment  VARCHAR2(20) PATH '$.sentiment',
               confidence NUMBER       PATH '$.confidence'
          )
     )
j;


SENTIMENT                      CONFIDENCE
-------------------- --------------------
negative                .6211975044276729
neutral                 .3510681601407111
positive              .027734335431616075

推荐阅读