In MariaDB, JSON_DEPTH() è una funzione integrata che ti consente di controllare la profondità di un documento JSON.
Accetta il documento JSON come argomento e restituisce la profondità massima del documento.
Sintassi
La sintassi è questa:
JSON_DEPTH(json_doc)
Dove json_doc è il documento JSON per il quale restituire la profondità.
Esempio
Ecco un esempio da dimostrare.
SELECT JSON_DEPTH('{ "name": "Wag" }'); Risultato:
+---------------------------------+
| JSON_DEPTH('{ "name": "Wag" }') |
+---------------------------------+
| 2 |
+---------------------------------+
In questo caso, la profondità è 2 .
Valori scalari e oggetti/array vuoti
I valori scalari o gli array o gli oggetti vuoti hanno una profondità di 1 :
SELECT
JSON_DEPTH('{}'),
JSON_DEPTH('[]'),
JSON_DEPTH(1); Risultato:
+------------------+------------------+---------------+
| JSON_DEPTH('{}') | JSON_DEPTH('[]') | JSON_DEPTH(1) |
+------------------+------------------+---------------+
| 1 | 1 | 1 |
+------------------+------------------+---------------+ Documento JSON più approfondito
Ecco un esempio che utilizza un documento JSON con una profondità di 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); Risultato:
+----------------------------+ | JSON_DEPTH(@json_document) | +----------------------------+ | 4 | +----------------------------+
Argomenti nulli
Se l'argomento è NULL , il risultato è NULL :
SELECT JSON_DEPTH(null); Risultato:
+------------------+ | JSON_DEPTH(null) | +------------------+ | NULL | +------------------+
JSON non valido
Il passaggio di JSON non valido restituisce NULL con un avviso:
SELECT JSON_DEPTH('{1}'); Risultato:
+-------------------+
| JSON_DEPTH('{1}') |
+-------------------+
| NULL |
+-------------------+
1 row in set, 1 warning (0.000 sec) Vediamo l'avviso:
SHOW WARNINGS; Risultato:
+---------+------+--------------------------------------------------------------------------------+ | Level | Code | Message | +---------+------+--------------------------------------------------------------------------------+ | Warning | 4038 | Syntax error in JSON text in argument 1 to function 'json_depth' at position 2 | +---------+------+--------------------------------------------------------------------------------+
Conteggio parametri errato
Non fornire argomenti genera un errore:
SELECT JSON_DEPTH(); Risultato:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'
È lo stesso quando fornisci troppi argomenti:
SELECT JSON_DEPTH('{"a": 1}', 2); Risultato:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'