Mysql
 SQL >> Database >  >> RDS >> Mysql

JSON_OBJECT(): creare un oggetto JSON da coppie chiave/valore in MySQL

La funzione JSON_OBJECT() di MySQL crea un oggetto JSON a partire da coppie chiave/valore. Ogni coppia viene fornita come due argomenti separati.

Il numero di argomenti deve essere pari. Puoi anche chiamare la funzione senza argomenti per ottenere un oggetto vuoto.

Sintassi

JSON_OBJECT([key, val[, key, val] ...])

Esempio 1 – Introduzione

SELECT JSON_OBJECT('City', 'Cairns', 'Population', 139693) AS 'Result';

Risultato:

------------------------------------------+
| Result                                   |
+------------------------------------------+
| {"City": "Cairns", "Population": 139693} |
+------------------------------------------+

Esempio 2 – Stringhe vuote

SELECT JSON_OBJECT('City', '', 'Population', 139693) AS 'Result';

Risultato:

------------------------------------+
| Result                             |
+------------------------------------+
| {"City": "", "Population": 139693} |
+------------------------------------+
SELECT JSON_OBJECT('', 'Cairns', 'Population', 139693) AS 'Result';

Risultato:

--------------------------------------+
| Result                               |
+--------------------------------------+
| {"": "Cairns", "Population": 139693} |
+--------------------------------------+

Esempio 3 – Lista vuota

SELECT JSON_OBJECT() AS 'Result';

Risultato:

+--------+
| Result |
+--------+
| {}     |
+--------+

Esempio 4 – Valori NULL

SELECT JSON_OBJECT('City', 'Cairns', 'Population', NULL) AS 'Result';

Risultato:

----------------------------------------+
| Result                                 |
+----------------------------------------+
| {"City": "Cairns", "Population": null} |
+----------------------------------------+

La chiave, invece, non può essere NULL:

SELECT JSON_OBJECT('City', 'Cairns', NULL, 139693) AS 'Result';

Risultato:

ERROR 3158 (22032): JSON documents may not contain NULL member names.