JSON data type conversion
seekdb supports the CAST function to convert data of other types to JSON data and vice versa.
The following table describes the conversion rules for JSON data types.
| Other data type | CAST(other_type AS JSON) | CAST(JSON AS other_type) |
|---|---|---|
| JSON | No change | No change |
utf8mb4 character type | The characters are converted to JSON values and validated. | The value is serialized as an utf8mb4 string. |
binary character type | The value is first converted to utf8mb4 and then handled as an utf8mb4 character value. | The value is first serialized as an utf8mb4 string and then converted to a binary string. |
| NULL | An empty JSON value is returned. | N/A |
| Other types | Only scalar values are converted to JSON values that contain only one value. | If a JSON value contains only one scalar value that matches the target type, it is converted to the corresponding type. Otherwise, NULL is returned and an alert is generated. |
info
other_type specifies a data type other than JSON.
The following examples show how to convert data of other types to JSON data and vice versa.
SELECT CAST("123" AS JSON);
The preceding statement returns the following result:
+---------------------+
| CAST("123" AS JSON) |
+---------------------+
| 123 |
+---------------------+
1 row in set (0.001 sec)
SELECT CAST(null AS JSON);
The preceding statement returns the following result:
+--------------------+
| CAST(null AS JSON) |
+--------------------+
| NULL |
+--------------------+
1 row in set (0.001 sec)
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);
The preceding statement returns the following result:
+-------------------------------+--------+
| c1 | c2 |
+-------------------------------+--------+
| {"id": 16, "color": "orange"} | orange |
| {"id": 17, "color": "red"} | apple |
| {"id": 18, "color": "yellow"} | banana |
+-------------------------------+--------+
3 rows in set (0.003 sec)