当前位置: 代码网 > it编程>编程语言>Javascript > MySQL 中的 JSON_UNQUOTE 与 JSON_EXTRACT 使用示例详解

MySQL 中的 JSON_UNQUOTE 与 JSON_EXTRACT 使用示例详解

2025年12月11日 Javascript 我要评论
1. json_extract(json_doc, path)功能:从 json 字符串中提取指定路径的数据。参数:json_doc:要解析的 json 字符串(例如 b.settings)。path

1. json_extract(json_doc, path)

功能:从 json 字符串中提取指定路径的数据。
参数:
json_doc:要解析的 json 字符串(例如 b.settings)。
path:json 路径表达式,如 $.level 表示根对象下的 level 字段。
返回值:提取出的值,如果路径不存在则返回 null。

json_extract('{"level": "critical"}', '$.level')
-- 返回: "critical"(带引号的字符串)

2. json_unquote(json_value)

功能:将 json 提取结果中的引号去掉,返回原始值。
适用场景:当你需要直接操作提取的值而不是带引号的字符串时使用。

json_unquote(json_extract('{"level": "critical"}', '$.level'))
-- 返回: critical(不带引号)

实际应用

{
  "level": "critical",
  "description": "high severity alert"
}
json_unquote(json_extract(b.settings, '$.level')) as level
json_extract 提取出 "critical"。
json_unquote 将其转换为 critical,便于后续处理或展示。

处理嵌套 json 结构

如果 json 数据中存在嵌套结构,可以通过扩展路径表达式来提取嵌套值。

示例 1:提取嵌套对象字段

json_unquote(json_extract(b.settings, '$.metadata.region')) as region
假设 b.settings 如下
{
  "level": "critical",
  "metadata": {
    "env": "production",
    "region": "us-west"
  }
}
$.metadata.region 会提取 us-west

示例 2:提取数组元素

json_unquote(json_extract(b.settings, '$.notifications[0].name')) as first_notification
{
  "notifications": [
    { "name": "email", "type": "email" },
    { "name": "slack", "type": "slack" }
  ]
}
$.notifications[0].name 会提取 email。
3. 提取数组中的所有值
如果你需要提取整个数组或其中的所有元素,可以使用通配符 *。
示例:提取 notifications 数组中所有 name 字段
select json_unquote(json_extract(json_data, '$.notifications[*].name')) as names;
输出结果为:["email", "slack"](去除外层引号后仍然是字符串格式)。

如果路径不存在于 json 中,json_extract 会返回 null。
建议使用 ifnull() 或 coalesce() 来提供默认值。

到此这篇关于mysql 中的 json_unquote 与 json_extract 使用详解的文章就介绍到这了,更多相关mysql json_unquote与json_extract使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com