3

I have a MySQL JSON column containing values such as:

[33173,33386,24272,33499,33526,33347]

Would it be possible, with JSON functions, to cast each value in the array to string? The output would be:

["33173","33386","24272","33499","33526","33347"]

I'd like to avoid resorting to dirty REPLACE() calls.

1
  • What version of MySQL (i.e. what does SELECT VERSION(); return)? Commented Apr 29, 2022 at 22:47

1 Answer 1

4

If you use MySQL 8.0, you can use the JSON_TABLE() function to explode the array into rows, then cast them to CHAR(), then JSON_ARRAYAGG() to implode the rows back into a JSON array.

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;

Output:

+--------------------------------------------------------+
| j                                                      |
+--------------------------------------------------------+
| ["33173", "33386", "24272", "33499", "33526", "33347"] |
+--------------------------------------------------------+
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly the answer I was looking for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.