将逗号分隔的字符串迁移到 JSON 数组

huangapple go评论66阅读模式
英文:

Migrate comma separated string to json array

问题

我想将它们转换成JSON数组,以便我可以使用MySQL JSON数组类型及其关联的方法。
所以基本上我正在寻找一种方法,将technician,director,website designer转换为["technician","director","website designer"]在SQL中。

列表的长度是任意的。
我遇到的最大问题是如何在逗号分隔的字符串中的每个元素上应用SQL函数(例如,我可以运行JSON_QUOTE()在每个元素上),因为添加括号只是一个简单的CONCAT

解决方案应适用于MySQL 5.7。

英文:

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

得分: 9

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

英文:

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

huangapple
  • 本文由 发表于 2020年1月3日 18:17:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定