如何在mysql中替换JSON键的值

时间:2018-04-30 14:22:42

标签: mysql mysql-workbench

我有一个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"}}]

密钥不存在。

我需要用{"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中的previoustable记录中,但可能不会出现在this记录中

1 个答案:

答案 0 :(得分:0)

该列应为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对象,修改数据,然后将其序列化为字符串,并更新行。