MySql Json 替换数组值

Hem*_*ngh 5 mysql json mysql-5.7

如果值匹配某些条件,MySql Json 替换特定索引处的数组值

例子:

{
  "deploy": [
    "Infrastructure",
    "API Security"
  ],
  "operate": [
    "Pen Testing",
    "Bug Bounty"
  ]
}
Run Code Online (Sandbox Code Playgroud)

这里我想用基础设施工具代替基础设施的价值

在此示例中,基础设施的索引为 0,但这可能因其他行而异

我试图解决这个问题的查询是

update table_config 
set config = JSON_SET(config,JSON_SEARCH(config,'one',"Infrastructure"),"Infrastructure");
Run Code Online (Sandbox Code Playgroud)

哪个不运行

以下是我的表格:

CREATE TABLE `table_config` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `config` longtext,
  `type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
Run Code Online (Sandbox Code Playgroud)

Bil*_*win 4

结果JSON_SEARCH()不是有效的 JSON 路径。它被引用,就像 JSON 字符串值一样。注意双引号:

mysql> select json_search(config, 'one', 'Infrastructure') 
  from table_config;
+----------------------------------------------+
| json_search(config, 'one', 'Infrastructure') |
+----------------------------------------------+
| "$.deploy[0]"                                |
+----------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

因此,如果您尝试将其用作 JSON_SET() 中的路径参数,它将不起作用:

mysql> select json_set(config, json_search(config, 'one', 'Infrastructure'), 'Infrastructure')
  from table_config;
ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 1.
Run Code Online (Sandbox Code Playgroud)

要将其用作 JSON 路径,您必须删除这些引号:

mysql> select json_unquote(json_search(config, 'one', 'Infrastructure')) 
  from table_config;
+------------------------------------------------------------+
| json_unquote(json_search(config, 'one', 'Infrastructure')) |
+------------------------------------------------------------+
| $.deploy[0]                                                |
+------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

然后您可以在调用 JSON_SET() 时使用它:

mysql> select json_set(config, json_unquote(json_search(config, 'one', 'Infrastructure')), 'Infrastructure') 
  from table_config;
+------------------------------------------------------------------------------------------------+
| json_set(config, json_unquote(json_search(config, 'one', 'Infrastructure')), 'Infrastructure') |
+------------------------------------------------------------------------------------------------+
| {"deploy": ["Infrastructure", "API Security"], "operate": ["Pen Testing", "Bug Bounty"]}       |
+------------------------------------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)