简体   繁体   English

如何在 Oracle 中漂亮地格式化 JSON?

[英]How to pretty format JSON in Oracle?

I wanted to know if there is any way to format a JSON in Oracle (as does this web site example)我想知道是否有任何方法可以在 Oracle 中格式化 JSON(就像这个网站示例一样)

In XML I used:在 XML 中,我使用了:

SELECT XMLSERIALIZE(Document XMLTYPE(V_RESPONSE) AS CLOB INDENT SIZE = 2)
INTO V_RESPONSE
FROM DUAL;     

And it works very well.而且效果很好。

With Oracle 12c, you can use the JSON_QUERY() function with the RETURNING ... PRETTY clause :在 Oracle 12c 中,您可以JSON_QUERY()函数JSON_QUERY() RETURNING ... PRETTY子句一起使用:

PRETTY : Specify PRETTY to pretty-print the return character string by inserting newline characters and indenting PRETTY :指定PRETTY以通过插入换行符和缩进来漂亮地打印返回字符串

Expression :表达 :

JSON_QUERY(js_value, '$' RETURNING VARCHAR2(4000) PRETTY)

Demo on DB Fiddle : DB Fiddle 上的演示

with t as (select '{"a":1, "b": [{"b1":2}, {"b2": "z"}]}' js from dual)
select json_query(js, '$' returning varchar2(4000) pretty) pretty_js, js from t;

Yields :产量:

PRETTY_JS                 | JS
--------------------------|----------------------------------------
{                         | {"a":1, "b": [{"b1":2}, {"b2": "z"}]}
  "a" : 1,                | 
  "b" :                   |
  [                       |
    {                     |
      "b1" : 2            | 
    },                    |
    {                     |
      "b2" : "z"          |
    }                     |
  ]                       |
}                         |

When you're lucky enough to get to Oracle Database 19c, there's another option for pretty printing: JSON_serialize .当您有幸使用 Oracle Database 19c 时,还有另一个用于漂亮打印的选项: JSON_serialize

This allows you to convert JSON between VARCHAR2/CLOB/BLOB.这允许您在 VARCHAR2/CLOB/BLOB 之间转换 JSON。 And includes a PRETTY clause:并包含一个 PRETTY 子句:

with t as (
  select '{"a":1, "b": [{"b1":2}, {"b2": "z"}]}' js
  from dual
)
select json_serialize (
         js returning varchar2 pretty
       ) pretty_js,
       js
from   t;

PRETTY_JS               JS
{                       {"a":1, "b": [{"b1":2}, {"b2": "z"}]}  
  "a" : 1,
  "b" :
  [
    {
      "b1" : 2
    },
    {
      "b2" : "z"
    }
  ]
} 

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

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