0

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

1
  • You fell victim to one of the classic blunders - the most famous of which is "never get involved in a land war in Asia" - but only slightly less well-known is this: "Never put csv values in a table column!" Commented Nov 3, 2020 at 14:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this only works as long as your CSV elements do not contain embedded double quotes In such case nested replace will help.

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.