MySQL JSON_PRETTY() Function
In MySQL, the JSON_PRETTY()
function returns the specified JSON document with a pretty format.
JSON_PRETTY()
Syntax
Here is the syntax of the MySQL JSON_PRETTY()
function:
JSON_PRETTY(json)
Parameters
json
- Required. A JSON document string or a JSON type value.
Return value
The JSON_PRETTY()
function returns the specified JSON document with a pretty format.
The JSON_PRETTY()
function fortmats the JSON document according to the follows rules:
- Each array element or object member appears on a separate line, indented an additional level compared to its parent.
- Each indentation level adds two leading spaces.
- The comma that separates individual array elements or object members is printed before the newline character that separates two elements or members.
- The key and the value โโof an object member are separated by a colon followed by a space (
': '
). - An empty object or array appears on one line. No spaces is printed between the opening and closing brace.
- Special characters in string scalars and key names are escaped using the same rules as
JSON_QUOTE()
functions.
This function will return NULL
if the argument is NULL
.
If any parameter is not a valid JSON document, MySQL will give an error. You can use JSON_VALID()
to verify the JSON document.
JSON_PRETTY()
Examples
Here are some examples of JSON_PRETTY()
.
Format an array
SELECT JSON_PRETTY('[1, 2, 3]');
+--------------------------+
| JSON_PRETTY('[1, 2, 3]') |
+--------------------------+
| [
1,
2,
3
] |
+--------------------------+
Format an object
SELECT JSON_PRETTY('{"x": 1, "y": 2}');
+---------------------------------+
| JSON_PRETTY('{"x": 1, "y": 2}') |
+---------------------------------+
| {
"x": 1,
"y": 2
} |
+---------------------------------+
Format a complex object
SELECT JSON_PRETTY('{"x": 1, "y": [1, 2, 3], "z": {"a": "a", "b": true}}');
+------------------------------------------------------------------------------------------+
| JSON_PRETTY('{"x": 1, "y": [1, 2, 3], "z": {"a": "a", "b": true}}') |
+------------------------------------------------------------------------------------------+
| {
"x": 1,
"y": [
1,
2,
3
],
"z": {
"a": "a",
"b": true
}
} |
+------------------------------------------------------------------------------------------+