在 MySQL 中转换 JSON 数组值
Cast JSON array values in MySQL
我有一个 MySQL JSON 列包含以下值:
[33173,33386,24272,33499,33526,33347]
是否可以使用 JSON 函数将数组中的每个值都转换为字符串?输出将是:
["33173","33386","24272","33499","33526","33347"]
我想避免诉诸肮脏的 REPLACE()
电话。
如果您使用 MySQL 8.0,您可以使用 JSON_TABLE() function to explode the array into rows, then cast them to CHAR(), then JSON_ARRAYAGG() 将行分解回 JSON 数组。
set @j = '[33173,33386,24272,33499,33526,33347]';
select json_arrayagg(cast(i as char(5))) as j
from json_table(@j, '$[*]' columns (i int path '$')) j;
输出:
+--------------------------------------------------------+
| j |
+--------------------------------------------------------+
| ["33173", "33386", "24272", "33499", "33526", "33347"] |
+--------------------------------------------------------+
我有一个 MySQL JSON 列包含以下值:
[33173,33386,24272,33499,33526,33347]
是否可以使用 JSON 函数将数组中的每个值都转换为字符串?输出将是:
["33173","33386","24272","33499","33526","33347"]
我想避免诉诸肮脏的 REPLACE()
电话。
如果您使用 MySQL 8.0,您可以使用 JSON_TABLE() function to explode the array into rows, then cast them to CHAR(), then JSON_ARRAYAGG() 将行分解回 JSON 数组。
set @j = '[33173,33386,24272,33499,33526,33347]';
select json_arrayagg(cast(i as char(5))) as j
from json_table(@j, '$[*]' columns (i int path '$')) j;
输出:
+--------------------------------------------------------+
| j |
+--------------------------------------------------------+
| ["33173", "33386", "24272", "33499", "33526", "33347"] |
+--------------------------------------------------------+