Skip to content
Advertisement

Mysql comma seperated to json-array

I have some fields in the database that are comma selerated, something like: a,b,c,d,e

and I want to convert them into:

["a","b","c","d","e"]

I know how to do it in nodejs / any other language, but I need to do it directly on the mysql
Possible? Thanks

Advertisement

Answer

The simplest approach probably is to use string functions only:

select concat('["', replace(col, ',', '","'), '"]') js from mytable

Basically this turns a string 'a,b,c,d,e' to '["a","b","c","d","e"]' – which MySQL will happily understand as JSON, if you use JSON functions on it.

Note that this only works as long as your CSV elements do not contain embedded double quotes.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement