首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在json数组中使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT

问在json数组中使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT
EN

Stack Overflow用户
提问于 2018-08-17 09:08:37
回答 2查看 1.5K关注 0票数 0

我在mysql中有一个名为names的json类型列,它是一个简单的json数组(不是key/value)。对于简单的json数组字段,我找不到使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT的任何示例。

我知道在json字段类型中还有其他方法来操作json数组,但是是否可以将这些函数用于json数组呢?

例如,name字段包含["A","B","C"],如何使用这些函数对此json执行更新、插入和删除?

更新

查询必须从php脚本执行。

EN

回答 2

Stack Overflow用户

发布于 2018-08-17 09:27:10

您所引用的所有函数的工作方式与手册中所期望的和描述的完全相同;也就是说,如果某个值已经存在,JSON_SET将插入或替换;如果某个值不存在,JSON_INSERT将插入或替换;而JSON_REPLACE将替换先前存在的值。您可以使用JSON_ARRAY_INSERT和JSON_ARRAY_APPEND更容易地向JSON数组添加值。

代码语言:javascript
复制
-- extract second element
select json_extract('["A", "B", "C"]', '$[1]')
-- "B"

-- replace second element
select json_set('["A", "B", "C"]', '$[1]', 'D')
-- ["A", "D", "C"]

-- insert fourth element
select json_set('["A", "B", "C"]', '$[3]', 'E')
-- ["A", "B", "C", "E"]

-- attempt to insert second element fails as it already exists
select json_insert('["A", "B", "C"]', '$[1]', 'F')
-- ["A", "B", "C"]

-- use json_array_insert to insert a new second element and move the other elements right
select json_array_insert('["A", "B", "C"]', '$[1]', 'F')
-- ["A", "F", "B", "C"]

-- insert fourth element
select json_insert('["A", "B", "C"]', '$[3]', 'F')
-- ["A", "B", "C", "F"]

-- or use json_array_append to add an element at the end
select json_array_append('["A", "B", "C"]', '$', 'F')
-- ["A", "B", "C", "F"]

-- replace second element
select json_replace('["A", "B", "C"]', '$[1]', 'G')
-- ["A", "G", "C"]

-- attempt to replace non-existing element fails
select json_replace('["A", "B", "C"]', '$[3]', 'G')
-- ["A", "B", "C"]

dbfiddle演示

要在表中的列上使用这些函数,只需将上述调用中的["A", "B", "C"]替换为列名,例如:

代码语言:javascript
复制
create table test (j json);
insert into test values ('["A", "B", "C"]');
select json_array_insert(j, '$[1]', 'F') 
from test
-- ["A", "F", "B", "C"]

dbfiddle演示

票数 3
EN

Stack Overflow用户

发布于 2018-08-17 17:51:26

我想找到了解决办法

对于json数组,不可能按数组值使用JSON_EXTRACT、JSON_SET、JSON_REPLACE、JSON_INSERT,而且您必须知道每个值在json数组中的位置(我认为这是一个弱点)。

例如,要选择第二个值,可以使用$[1],但对于插入值,可以使用JSON_ARRAY_APPEND和JSON_ARRAY_INSERT。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51891984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档