JSON_DEPTH() – Find the Maximum Depth of a JSON Document in MySQL

In MySQL, the JSON_DEPTH() function returns the maximum depth of a JSON document.

When you call this function, you provide the JSON document as an argument.

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('{}') 'Result';

Result:

+--------+
| Result |
+--------+
|      1 |
+--------+

And here’s what happens if we add some data.

SELECT JSON_DEPTH('{"Name": "Homer"}') 'Result';

Result:

+--------+
| Result |
+--------+
|      2 |
+--------+

Example 2 – A Deeper Document

Here’s another example, this time using a slightly deeper JSON document.

SET @data = '{  
    "Person": {    
       "Name": "Homer", 
       "Age": 39,
       "Hobbies": ["Eating", "Sleeping"]  
    }
 }';
SELECT JSON_DEPTH(@data) 'Result';

Result:

+--------+
| Result |
+--------+
|      4 |
+--------+