SQL >> Base de Datos >  >> RDS >> MariaDB

Extraer datos de JSON en MariaDB con JSON_EXTRACT()

JSON_EXTRACT() recupera datos de un documento JSON de acuerdo con una o más rutas. Su comportamiento depende de cuántos valores coincidan: una sola coincidencia produce un único valor, mientras que varias coincidencias se agrupan en un array.

Sintaxis

JSON_EXTRACT(json_doc, path[, path] ...)

El primer argumento es el documento; cada path posterior es una ubicación dentro de él.

Extraer un valor

SET @json_document = ' { "name": "Wag", "type": "Dog", "weight": 20 } '; SELECT JSON_EXTRACT(@json_document, '$.name');

Resultado:

+----------------------------------------+ | JSON_EXTRACT(@json_document, '$.name') | +----------------------------------------+ | "Wag" | +----------------------------------------+

Extraer varios valores

SET @json_document = ' { "name": "Wag", "type": "Dog", "weight": 20 } '; SELECT JSON_EXTRACT(@json_document, '$.name', '$.weight');

Resultado:

+----------------------------------------------------+ | JSON_EXTRACT(@json_document, '$.name', '$.weight') | +----------------------------------------------------+ | ["Wag", 20] | +----------------------------------------------------+

Varias rutas siempre generan un array, incluso cuando solo aparece un valor.

Rutas que no resuelven

Una única ruta inexistente devuelve NULL:

SET @json_document = ' { "name": "Wag", "type": "Dog", "weight": 20 } '; SELECT JSON_EXTRACT(@json_document, '$.color');

Resultado:

+-----------------------------------------+ | JSON_EXTRACT(@json_document, '$.color') | +-----------------------------------------+ | NULL | +-----------------------------------------+

Pero si mezclas una ruta válida con una inválida, obtienes un array con el único valor que coincidió:

SET @json_document = ' { "name": "Wag", "type": "Dog", "weight": 20 } '; SELECT JSON_EXTRACT(@json_document, '$.name', '$.color');

Resultado:

+---------------------------------------------------+ | JSON_EXTRACT(@json_document, '$.name', '$.color') | +---------------------------------------------------+ | ["Wag"] | +---------------------------------------------------+

Arrays

SET @json_document = ' { "_id" : 1, "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] } '; SELECT JSON_EXTRACT(@json_document, '$.awards[0]');

Resultado:

+---------------------------------------------+ | JSON_EXTRACT(@json_document, '$.awards[0]') | +---------------------------------------------+ | "Top Dog" | +---------------------------------------------+

Los arrays empiezan en cero, así que $.awards[0] es el primer elemento.

Objetos anidados

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_EXTRACT( @json_document, '$.details.awards.New York Marathon' ) AS Result;

Resultado:

+---------------+ | Result | +---------------+ | "Fastest Dog" | +---------------+

Acorta la ruta a $.details.awards y obtendrás el objeto de premios completo:

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_EXTRACT( @json_document, '$.details.awards' ) AS Result;

Resultado:

+---------------------------------------------------------------------------------------------------+ | Result | +---------------------------------------------------------------------------------------------------+ | {"Florida Dog Awards": "Top Dog", "New York Marathon": "Fastest Dog", "Sumo 2020": "Biggest Dog"} | +---------------------------------------------------------------------------------------------------+

Hacer legible la salida

Anida la llamada dentro de JSON_DETAILED() para una vista más ordenada:

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_DETAILED( JSON_EXTRACT( @json_document, '$.details.awards' ) ) AS Result;

Resultado:

+------------------------------------------------+ | Result | +------------------------------------------------+ | { "Florida Dog Awards": "Top Dog", "New York Marathon": "Fastest Dog", "Sumo 2020": "Biggest Dog" } | +------------------------------------------------+

Argumentos NULL

SELECT JSON_EXTRACT(null, '$.type'), JSON_EXTRACT('{"a":1}', null);

Resultado:

+------------------------------+-------------------------------+ | JSON_EXTRACT(null, '$.type') | JSON_EXTRACT('{"a":1}', null) | +------------------------------+-------------------------------+ | NULL | NULL | +------------------------------+-------------------------------+

Errores en el número de argumentos

SELECT JSON_EXTRACT();

Resultado:

ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_EXTRACT'

Demasiados pocos argumentos dispara el mismo error:

SELECT JSON_EXTRACT('{ "a": 1}');

Resultado:

ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_EXTRACT'