I've a JSON column from where I'm extracting values. All goes good, except I'm not able to convert an array inside the JSON Object to a comma separated string. Below is the structure similar to what I have.
id | name | data |
---|---|---|
... | ... | ... |
234 | AAA | { "..." "options": [ "Option A", "Option B", "Option C" ], "..." } |
... | ... | ... |
Now I'm extracting the data like this:
SELECT
`id`,
`name`,
JSON_UNQUOTE( JSON_EXTRACT( `data`, '$.options' ) ) AS `options`
FROM `my_table`;
Result I'm getting:
id | name | data |
---|---|---|
... | ... | ... |
234 | AAA | ["Option A", "Option B", "Option C"] |
... | ... | ... |
Result I want:
id | name | data |
---|---|---|
... | ... | ... |
234 | AAA | "Option A", "Option B", "Option C" |
... | ... | ... |
How can I do this in MySQL? It's like implode function in php.
I've seen some answers that uses nested REPLACE
but remember that the value itself may contain square brackets.
Assuming you are using mysql 8.0 then you can use JSON_TABLE
with CROSS JOIN
and GROUP_CONCAT
to achieve this:
Try below query:
select t1.id,t1.name, group_concat(t2.data_ )
from test t1
cross join
json_table(t1.data->'$.options', '$[*]' columns(data_ varchar(10) path '$'))t2
group by 1,2
If you want to surround all the values in quotes then replace group_concat(t2.data_ )
with group_concat(concat('"',t2.data_,'"' ))
in above query
Explanation
In your question you want to get the values of options
array of the JSON in to comma separated string. So the steps of the solution is:
Step 1. Get the array data from JSON: Here by using ->
operator we are able to fetch the data from data
field. data->'$.options'
will return the array in JSON format.
Step 2. Unnest all the elements of the array: Here JSON_TABLE
( Reference ) will do the things for us. see below example
select * from json_table(
'["Option A","Option B","Option C"]',
'$[*]' columns(data_ varchar(10) path '$'))t
Result:
data_
Option A
Option B
Option C
Step 3. Cross join the unnest records: After unnest the array CROSS JOIN
it with main table, which will return one row against each records returns by JSON_TABLE
. In below example you will get 3 rows against id 234 because there are 3 elements in array.
select t1.id,t1.name,t2.data_
from test t1
cross join
json_table(t1.data->'$.options', '$[*]' columns(data_ varchar(10) path '$'))t2
Result:
id name data_
234 AAA Option A
234 AAA Option B
234 AAA Option C
Step 4. Group the results: In final step use GROUP_CONCAT
( Reference ) to group all the records by id
, name
etc. to get the desired output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.