本文共 2958 字,大约阅读时间需要 9 分钟。
MySQL 5.7 版本后开始支持 JSON 类型字段,本文将详细介绍 JSON_EXTRACT 函数的使用方法,帮助您获取 MySQL 中的 JSON 数据。
JSON_EXTRACT 函数可以通过简写形式进行调用,具体如下:
->
。->>
。本文将基于这些简写形式进行介绍。
为了演示 JSON_EXTRACT 的使用,我们先创建一个示例表 test_json
,字段 content
为 JSON 类型。
CREATE TABLE `test_json` ( `id` int(11) NOT NULL AUTO_INCREMENT, `content` json DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
插入测试数据:
INSERT INTO `test_json` (`content`) VALUES ('{\"name\":\"tom\",\"age\":18,\"score\":[100,90,87],\"address\":{\"province\":\"湖南\",\"city\":\"长沙\"}}');INSERT INTO `test_json` (`content`) VALUES ('[1, "apple", "red", {"age": 18, "name": "tom"}]');
表结构如下:
id | content |
---|---|
1 | {"age": 18, "name": "tom", "score": [100, 90, 87], "address": {"province": "湖南", "city": "长沙"}} |
2 | [1, "apple", "red", {"age": 18, "name": "tom"}] |
JSON_EXTRACT 函数的第一个参数是 JSON 数据,第二个参数是 JSON 路径。
$.name
表示获取 JSON 数据中 key 为 "name" 的 value。$[i]
表示获取 JSON 数组中索引为 i 的元素。示例:
-- 获取 "tom"select json_extract(content, '$.name') from test_json where id = 1;-- 简写方式select content -> '$.name' from test_json where id = 1;
如果 value 本身是字符串,会被引号包裹,导致转义。为了去除引号,可以使用 json_unquote
:
-- 解除引号,得到 "tom"select json_unquote(json_extract(content, '$.name')) from test_json where id = 1;-- 简写方式select content ->> '$.name' from test_json where id = 1;
如果需要获取 JSON 数组中的某个元素,可以使用索引。
-- 获取 "apple"select json_extract(content, '$[1]') from test_json where id = 2;-- 简写方式select content -> '$[1]' from test_json where id = 2;
同样,数组中的元素如果是字符串,会被引号包裹,使用 json_unquote
可以去除引号。
-- 解除引号,得到 "apple"select json_unquote(json_extract(content, '$[1]')) from test_json where id = 2;-- 简写方式select content ->> '$[1]' from test_json where id = 2;
JSON_EXTRACT 可以处理嵌套的 JSON 数据。
示例:
-- 获取 87select content -> '$.score[2]' from test_json where id = 1;-- 获取 18select content -> '$[3].age' from test_json where id = 2;
JSON_EXTRACT 可以返回多个路径的数据组合成数组。
示例:
-- 获取 age 和 scoreselect json_extract(content, '$.age', '$.score') from test_json where id = 1;-- 结果:[18, [100, 90, 87]]-- 获取 name、地址省市select json_extract(content, '$.name', '$.address.province', '$.address.city') from test_json where id = 1;-- 结果:["tom", "湖南", "长沙"]
*
可以表示匹配所有符合条件的键。
示例:
-- 获取所有 key 为 "name" 的值select content -> '$*.name' from test_json where id = 3;-- 结果:["一年三班", "中央公园"]-- 获取所有嵌套中的 name 值select content -> '$**.name' from test_json where id = 3;-- 结果:["tom", "一年三班", "marry", "Bob", "中央公园"]-- 获取朋友数组中的 nameselect content -> '$.friend[*].name' from test_json where id = 3;-- 结果:["marry", "Bob"]
如果 JSON 路径不存在,JSON_EXTRACT 会返回 NULL。
示例:
-- 寻找不存在的路径select json_extract(content, '$.price') from test_json where id = 1;-- 结果:NULL
JSON_EXTRACT 函数适用于以下场景:
通过合理运用 JSON_EXTRACT,您可以高效地提取和处理 JSON 数据,满足开发需求。
转载地址:http://wpbfk.baihongyu.com/