PLSQL:删除Json中不需要的双引号

时间:2019-06-24 10:42:48

标签: sql json oracle

我有一个这样的Json(它包含在clob变量中):

{"id": "33", "type": "abc", "val": "2", "cod": "", "sg1": "1", "sg2": "1"}
{"id": "359", "type": "abcef", "val": "52", "cod": "aa", "sg1": "", "sg2": "0"}
…

我需要从"idvalsg1的值中删除sg2

有可能吗?

例如,我需要获取此信息:

{"id": 33, "type": "abc", "val": 2, "cod": "", "sg1": 1, "sg2": 1}
{"id": 359, "type": "abcef", "val": 52, "cod": "aa", "sg1": , "sg2": 0}
…

1 个答案:

答案 0 :(得分:3)

如果您使用的是Oracle 12(R2?)或更高版本,则可以将JSON转换为适当的数据类型,然后再将其转换回JSON。

Oracle 18安装程序

CREATE TABLE test_data ( value CLOB );
INSERT INTO test_data ( value )
  VALUES ( '{"id": "33", "type": "abc", "val": "2", "cod": "", "sg1": "1", "sg2": "1"}' );
INSERT INTO test_data ( value )
  VALUES ( '{"id": "359", "type": "abcef", "val": "52", "cod": "aa", "sg1": "", "sg2": "0"}' );

查询

SELECT JSON_OBJECT(
         'id'   IS j.id,
         'type' IS j.typ,
         'val'  IS j.val,
         'cod'  IS j.cod,
         'sg1'  IS j.sg1,
         'sg2'  IS j.sg2
       ) AS JSON
FROM   test_data t
       CROSS JOIN
       JSON_TABLE(
         t.value,
         '$'
         COLUMNS
           id  NUMBER(5,0) PATH '$.id',
           typ VARCHAR2(10) PATH '$.type',
           val NUMBER(5,0) PATH '$.val',
           cod VARCHAR2(10) PATH '$.cod',
           sg1 NUMBER(5,0) PATH '$.sg1',
           sg2 NUMBER(5,0) PATH '$.sg2'
       ) j

输出

| JSON                                                             |
| :--------------------------------------------------------------- |
| {"id":33,"type":"abc","val":2,"cod":null,"sg1":1,"sg2":1}        |
| {"id":359,"type":"abcef","val":52,"cod":"aa","sg1":null,"sg2":0} |

或者,如果要使用正则表达式(如果可以选择,则不应该使用正则表达式,而应使用适当的JSON解析器),然后:

查询2

SELECT REGEXP_REPLACE(
         REGEXP_REPLACE(
           value,
           '"(id|val|sg1|sg2)": ""',
           '"\1": "null"'
         ),
         '"(id|val|sg1|sg2)": "(\d+|null)"',
         '"\1": \2'
       ) AS JSON
FROM   test_data

输出

| JSON                                                                        |
| :-------------------------------------------------------------------------- |
| {"id": 33, "type": "abc", "val": 2, "cod": "", "sg1": 1, "sg2": 1}          |
| {"id": 359, "type": "abcef", "val": 52, "cod": "aa", "sg1": null, "sg2": 0} |

db <>提琴here