gpt4 book ai didi

mysql - 如何替换mysql中JSON键的值

转载 作者:行者123 更新时间:2023-11-29 17:38:59 27 4
gpt4 key购买 nike

我有一个 mysql JSON 列,例如:

column       value
data [{ "report1": { "result": "5"}, "report2": {"result": "6"}, "report3": {"a": "4"}}, {"report1": { "result": "9"},"report4": {"details": "<b>We need to show the details here</b>"}, "report3": {"result": "5"}}]

另一个数据实例是:

[{ "report1": { "result": "5"}, "report2": {"result": "6"}, "report3": {"a": "4"}}, {"report1": { "result": "9"}, "report3": {"result": "5"},"report4": {"details": "<b>We need to show the details here</b>"}}]

在上面的记录中,键出现在第二个索引上。

在此:

[{ "report1": { "result": "5"}, "report2": {"result": "6"}, "report3": {"a": "4"}}, {"report1": { "result": "9"}, "report3": {"result": "5"}}]

key 不存在。

我需要替换{"details": "<b>We need to show the details here</b>"} ,即键report4的值仅 [] ,我现在需要这份报告中的数据。

实际上,仅针对该键,生成数据的逻辑已从 XML 数据更改为 JSON,因此,我们需要将其替换为空数组(现在的目标类型),而不影响其他数据。

有没有直接的解决办法?我避免在这里创建过程。

因此,目标数据将是:

[{ "report1": { "result": "5"}, "report2": {"result": "6"}, "report3": {"a": "4"}}, {"report1": { "result": "9"},"report4": [], "report3": {"result": "5"}}]

是的,JSON 中的键不一致,这意味着键可能出现在 next 中或previous记录在 table但可能不会出现在 this 中记录一下。

最佳答案

该列的类型应为 JSON有效地使用 MySQL 的 JSON 功能。然后使用JSON modification functions ,如JSON_REPLACE .

由于每个值都包含一个 JSON 数组,其大小可能无法提前知道,因此您可以创建一个小型实用函数来修改数组中的每个元素。

create function modify_json(val json)
returns json
deterministic
begin
declare len int default json_length(val);
declare i int default 0;

while i < len do
# Replace the report4 property of the i'th element with an empty list
set val = json_replace(val, concat('$[', i, '].report4'), '[]');
set i = i + 1;
end while;

return val;
end;

使用您的实用函数,更新记录:

update table set data = modify_json(data)
where json_contains_path(data, 'one', '$[*].report4');

在本例中,至少包含一个具有 report4 属性的元素的记录将根据 modify_json 函数进行更新。您可以使用多个更新命令来实现相同的效果,这些命令分别对 JSON 数组的每个索引进行操作。

如果由于某种原因列不能是 JSON 类型,那么您可以允许 MySQL 强制数据,或者您的程序可以将字符串编码为 JSON 对象,修改数据,然后将其序列化为字符串,然后更新行。

关于mysql - 如何替换mysql中JSON键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com