Skip to main content
Version: V1.4.1

Convert JSON data types

seekdb supports the CAST function for converting between JSON and other data types.

The following table describes the conversion rules for JSON data types.

Other data typesCAST(other_type AS JSON)CAST(JSON AS other_type)
JSONNo change.No change.
utf8mb4 character typeThe characters are converted to JSON values and validated.The data is serialized into an utf8mb4 string.
binary character typeThe value is converted to utf8mb4 and then processed as an utf8mb4 character value.The value is serialized into an utf8mb4 string and then converted to a binary string.
NULLAn empty JSON value is returned.Not applicable.
Other typesOnly scalar values are converted to JSON values containing that single value.If the JSON value contains only one scalar value that matches the target type, it is converted to the corresponding type; otherwise, NULL is returned and a warning is issued.
info

other_type specifies a data type other than JSON.

Here are some conversion examples:

SELECT CAST("123" AS JSON);
+---------------------+
| CAST("123" AS JSON) |
+---------------------+
| 123 |
+---------------------+
1 row in set

SELECT CAST(null AS JSON);
+--------------------+
| CAST(null AS JSON) |
+--------------------+
| NULL |
+--------------------+
1 row in set

CREATE TABLE tj1 (c1 JSON,c2 VARCHAR(20));
INSERT INTO tj1 VALUES ('{"id": 17, "color": "red"}','apple'),('{"id": 18, "color": "yellow"}', 'banana'),('{"id": 16, "color": "orange"}','orange');
SELECT * FROM tj1 ORDER BY CAST(JSON_EXTRACT(c1, '$.id') AS UNSIGNED);
+-------------------------------+--------+
| c1 | c2 |
+-------------------------------+--------+
| {"id": 16, "color": "orange"} | orange |
| {"id": 17, "color": "red"} | apple |
| {"id": 18, "color": "yellow"} | banana |
+-------------------------------+--------+
3 rows in set