mysql解析json字符串
时间: 2023-05-09 17:00:30 浏览: 111
MySQL从5.7版本开始支持JSON数据类型,可以存储JSON格式的数据,也可以解析JSON字符串中的数据。解析JSON字符串可以使用MySQL的JSON函数。
例如,假设有一个JSON字符串:
```json
{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}
```
如果需要提取其中的数据,可以使用以下JSON函数:
1. JSON_EXTRACT():提取JSON字符串中指定路径的数据
```MySQL
SELECT JSON_EXTRACT('{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}', '$.name');
-- 输出结果为 "Tom"
SELECT JSON_EXTRACT('{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}', '$.hobbies[0]');
-- 输出结果为 "reading"
```
2. JSON_KEYS():返回JSON字符串中所有的键名
```MySQL
SELECT JSON_KEYS('{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}');
-- 输出结果为 ["name", "age", "hobbies"]
```
3. JSON_LENGTH():返回JSON字符串中某个键名对应的值的长度或元素的个数
```MySQL
SELECT JSON_LENGTH('{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}', '$.hobbies');
-- 输出结果为 2
```
4. JSON_TYPE():返回JSON字符串中某个键名对应的值的类型
```MySQL
SELECT JSON_TYPE('{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}', '$.name');
-- 输出结果为 "STRING"
```
如果要在MySQL中存储JSON数据类型,则可以使用以下语法:
```MySQL
CREATE TABLE mytable (
id INT PRIMARY KEY,
info JSON
);
```
可以使用INSERT语句插入JSON数据:
```MySQL
INSERT INTO mytable VALUES (1, '{"name": "Tom", "age": 18, "hobbies": ["reading", "swimming"]}');
```
使用SELECT语句查询JSON数据:
```MySQL
SELECT info->'$.name' AS name, info->'$.age' AS age, info->'$.hobbies[0]' AS hobby
FROM mytable WHERE id = 1;
```
输出结果为:
```
+------+-----+---------+
| name | age | hobby |
+------+-----+---------+
| Tom | 18 | reading |
+------+-----+---------+
```
阅读全文