In MariaDB, JSON_DEPTH()
is a built-in function that allows you to check the depth of a JSON document.
It accepts the JSON document as an argument, and returns the maximum depth of the document.
Syntax
The syntax goes like this:
JSON_DEPTH(json_doc)
Where json_doc
is the JSON document for which to return the depth.
Example
Here’s an example to demonstrate.
SELECT JSON_DEPTH('{ "name": "Wag" }');
Result:
+---------------------------------+ | JSON_DEPTH('{ "name": "Wag" }') | +---------------------------------+ | 2 | +---------------------------------+
In this case, the depth is 2
.
Scalar Values & Empty Objects/Arrays
Scalar values or empty arrays or objects have a depth of 1
:
SELECT
JSON_DEPTH('{}'),
JSON_DEPTH('[]'),
JSON_DEPTH(1);
Result:
+------------------+------------------+---------------+ | JSON_DEPTH('{}') | JSON_DEPTH('[]') | JSON_DEPTH(1) | +------------------+------------------+---------------+ | 1 | 1 | 1 | +------------------+------------------+---------------+
Deeper JSON Document
Here’s an example that uses a JSON document with a depth of 4
:
SET @json_document = '
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20,
"awards" : {
"Florida Dog Awards" : "Top Dog",
"New York Marathon" : "Fastest Dog",
"Sumo 2020" : "Biggest Dog"
}
}
}
';
SELECT JSON_DEPTH(@json_document);
Result:
+----------------------------+ | JSON_DEPTH(@json_document) | +----------------------------+ | 4 | +----------------------------+
Null Arguments
If the argument is NULL
, the result is NULL
:
SELECT JSON_DEPTH(null);
Result:
+------------------+ | JSON_DEPTH(null) | +------------------+ | NULL | +------------------+
Invalid JSON
Passing invalid JSON results in NULL
with a warning:
SELECT JSON_DEPTH('{1}');
Result:
+-------------------+ | JSON_DEPTH('{1}') | +-------------------+ | NULL | +-------------------+ 1 row in set, 1 warning (0.000 sec)
Let’s see the warning:
SHOW WARNINGS;
Result:
+---------+------+--------------------------------------------------------------------------------+ | Level | Code | Message | +---------+------+--------------------------------------------------------------------------------+ | Warning | 4038 | Syntax error in JSON text in argument 1 to function 'json_depth' at position 2 | +---------+------+--------------------------------------------------------------------------------+
Incorrect Parameter Count
Providing no arguments results in an error:
SELECT JSON_DEPTH();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'
It’s the same when you provide too many arguments:
SELECT JSON_DEPTH('{"a": 1}', 2);
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'