简体   繁体   中英

How to return JSON_ARRAY using an GROUP_CONCAT

I've try return json object using "concat" and "group_concat" functions. Problem is that I need to use group_concat but I want to have a valid JSON structure. What I do wrong?

  1. {"a":"a", "b": "b", "id": null}
  2. [{"id": "123"}]

...

SELECT JSON_REPLACE((
                  SELECT JSON_OBJECT(
                             'a', 'a',
                             'b', 'b',
                             'id', null
                           )), '$.id', (
                  SELECT CONCAT(
                             '[', group_concat(JSON_OBJECT(
                          'id',
                          '123')),
                             ']'))
     )

result: {"a": "a", "b": "b", "id": "[{\\"id\\": \\"123\\"}]"}

expected: {"a": "a", "b": "b", "id": [{"id": "123"}]}

Extra CAST ing AS JSON for the third argument of JSON_REPLACE fixes the issue :

SELECT JSON_REPLACE((
                  SELECT JSON_OBJECT(
                             'a', 'a',
                             'b', 'b',
                             'id', null
                           )), '$.id', 
                         CAST( CONCAT('[', GROUP_CONCAT(
                                            JSON_OBJECT('id', '123')),
                                      ']') AS JSON )) as "Result JSON"
Result :
{
  "a": "a",
  "b": "b",
  "id": [
    {
      "id": "123"
    }
  ]
}

Demo

this is what you need JSON_ARRAYAGG

  SELECT JSON_REPLACE((SELECT JSON_OBJECT(
                             'a', 'a',
                             'b', 'b',
                             'id', null
                           )), '$.id', 
            (SELECT JSON_ARRAYAGG(JSON_OBJECT('id','123')))           
  )

if not using JSON_ARRAYAGG

  SELECT JSON_REPLACE((SELECT JSON_OBJECT(
                             'a', 'a',
                             'b', 'b',
                             'id', null
                           ))
            , '$.id'
            ,  (SELECT JSON_ARRAY(CAST(group_concat(JSON_OBJECT('id','123')) as json)))
   )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM