No MariaDB,
JSON_DEPTH() é uma função integrada que permite verificar a profundidade de um documento JSON. Ele aceita o documento JSON como argumento e retorna a profundidade máxima do documento.
Sintaxe
A sintaxe fica assim:
JSON_DEPTH(json_doc) Onde
json_doc é o documento JSON para o qual retornar a profundidade. Exemplo
Aqui está um exemplo para demonstrar.
SELECT JSON_DEPTH('{ "name": "Wag" }'); Resultado:
+---------------------------------+
| JSON_DEPTH('{ "name": "Wag" }') |
+---------------------------------+
| 2 |
+---------------------------------+ Neste caso, a profundidade é
2 . Valores escalares e objetos/matrizes vazios
Valores escalares ou matrizes ou objetos vazios têm uma profundidade de
1 :SELECT
JSON_DEPTH('{}'),
JSON_DEPTH('[]'),
JSON_DEPTH(1); Resultado:
+------------------+------------------+---------------+
| JSON_DEPTH('{}') | JSON_DEPTH('[]') | JSON_DEPTH(1) |
+------------------+------------------+---------------+
| 1 | 1 | 1 |
+------------------+------------------+---------------+ Documento JSON mais profundo
Aqui está um exemplo que usa um documento JSON com profundidade de
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); Resultado:
+----------------------------+ | JSON_DEPTH(@json_document) | +----------------------------+ | 4 | +----------------------------+
Argumentos nulos
Se o argumento for
NULL , o resultado é NULL :SELECT JSON_DEPTH(null); Resultado:
+------------------+ | JSON_DEPTH(null) | +------------------+ | NULL | +------------------+
JSON inválido
Passando resultados JSON inválidos em
NULL com um aviso:SELECT JSON_DEPTH('{1}'); Resultado:
+-------------------+
| JSON_DEPTH('{1}') |
+-------------------+
| NULL |
+-------------------+
1 row in set, 1 warning (0.000 sec) Vejamos o aviso:
SHOW WARNINGS; Resultado:
+---------+------+--------------------------------------------------------------------------------+ | Level | Code | Message | +---------+------+--------------------------------------------------------------------------------+ | Warning | 4038 | Syntax error in JSON text in argument 1 to function 'json_depth' at position 2 | +---------+------+--------------------------------------------------------------------------------+
Contagem de parâmetros incorreta
Não fornecer argumentos resulta em um erro:
SELECT JSON_DEPTH(); Resultado:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'
É o mesmo quando você fornece muitos argumentos:
SELECT JSON_DEPTH('{"a": 1}', 2); Resultado:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_DEPTH'