5

I have an old database, where some columns have comma separated strings stored like this technician,director,website designer

I want to convert them to a JSON array, so I can use the MySQL JSON array type and the methods associated with it.
So basically I am looking for a method to convert technician,director,website designer to ["technician","director","website designer"] in SQL.

The length of the list is arbitrary. The biggest struggle I am having is how to apply a SQL function on each element in the comma separated string, (So I for example can run the JSON_QUOTE() on each element) as adding the brackets are just a simple CONCAT.

The solution should be for MySQL 5.7.

1 Answer 1

10

You can use REPLACE to get the expected string:

SELECT CONCAT('["', REPLACE('technician,director,website designer', ',', '","'), '"]')
-- ["technician","director","website designer"]

Using JSON_VALID you can check if the result of the conversion is a valid JSON value:

SELECT JSON_VALID(CONCAT('["', REPLACE('technician,director,website designer', ',', '","'), '"]'))
-- 1

demo on dbfiddle.uk

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

1 Comment

Nice! Simple solution, did not think of that. I had one entry which was invalid, because it had a ", but, I just added a replace to escape it.

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.