Rewrite the title as: Concatenate JSON array to string in MySQL
P粉935883292
P粉935883292 2023-09-06 14:59:38
0
1
620

I'm looking for a way to concatenate JSON arrays into delimited strings in MySQL.

Below is an example using the nestedREPLACE()function to replace characters in a string.

SELECT REPLACE(REPLACE(REPLACE(JSON_KEYS('{ "foo": "I am foo", "bar": "I am bar", "baz": "I am baz" }'), '["', ''), '", "', '|'), '"]', '') AS value;

Return results...

bar|baz|foo

Is there a native way to do this without having to do some hacky stuff like this?

P粉935883292
P粉935883292

reply all (1)
P粉952365143

You are asking for JSON to CSV conversion using keys instead of values. The real "problem" is using keys, but this can be achieved in a cleaner way. I don't think this way is cleaner, but you might find it more elegant. Just to be extra certain: No, there isn't any native way in MySQL that does what you need.

SELECT GROUP_CONCAT(json_source.a_key SEPARATOR '|') FROM JSON_TABLE( JSON_KEYS('{ "foo": "I am foo", "bar": "I am bar", "baz": "I am baz" }'), "$[*]" COLUMNS(a_key TEXT PATH '$') ) AS json_source;

JSON_TABLEis a powerful tool, but requires reading and a lot of communication to understand. I myself am still in the communication stage.GROUP_CONCATworks like you would expect, but vertically.

Edit: You can also refer to thisSimilar question.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!