首页 > 解决方案 > 使用 JSON_ARRAY_APPEND 将大数组插入 JSON 文档

问题描述

我正在使用JSON_ARRAY_APPEND更新表中现有条目中的数组对象。

我通过代码和查询看起来如下:

UPDATE table t1
        SET t1.value = JSON_ARRAY_APPEND('[]', '$', JSON_OBJECT('desc', '${desc}', 
        'hosts', '[${hosts}]'))
        WHERE  t1.key = '${key1}
    

我的结果value如下所示:

[{"desc": "this is desc", "hosts": "[host1,host2, host3]"}] 

所需的输出value是:

[{"desc": "this is desc", "hosts": ["host1","host2","host3"]"}] 

标签: mysqlarraysjsonsql-updatemysql-json

解决方案


``

SELECT CONCAT('"', REPLACE('${hosts}', ',', '","'), '"');
UPDATE table t1
SET t1.value = JSON_ARRAY_APPEND('[]', '$', JSON_OBJECT('desc', '${desc}', 'hosts', '[${hosts}]'))
WHERE  t1.key = '${key1};


SET @host =  'host1,host2, host3';
UPDATE table t1
SET t1.value = JSON_ARRAY(
JSON_OBJECT(
'desc', 'this is desc', 
'hosts',
JSON_ARRAY(                           
SUBSTRING_INDEX(@host, ',', 1),
SUBSTRING_INDEX(SUBSTRING_INDEX(@host, ',', 2), ',', -1) ,
SUBSTRING_INDEX(SUBSTRING_INDEX(@host, ',', 3), ',', -1)))) ;

''


推荐阅读