MySQL JSON_OBJECT() with some fields already containing JSON String

喜夏-厌秋 提交于 2019-12-11 08:06:11

问题


How to get a JSON_OBJECT() of 3 columns whose some contains already a JSON format string.

Here is my example with info field that contains a json string, so all this object is escaped :

SELECT 
    T1.id, 
    CONCAT(
        '{"elements": [',
        GROUP_CONCAT(
            JSON_OBJECT(
                'type',  T2.`type`,
                'data',  T2.`data`,
                'info',  T2.`info`  <<-- JSON stored string in varchar(100)
            )
        ),
        ']}'
    ) AS `elements`,
FROM `table` T1
INNER JOIN `table2` T2
    ON T1.`id` = T2.`fk_t1_id`
GROUP BY T1.`id`

Maybe, use the new storage functions for JSON format will be better, but I didn't test it yet. What do you think ?


回答1:


Best solution I found is to use JSON_MERGE() in combination with JSON_OBJECT() and CONCAT()

SELECT 
    T1.id, 
    CONCAT(
        '{"elements": [',
        GROUP_CONCAT(
            JSON_MERGE(
                JSON_OBJECT(
                    'type',  T2.`type`,
                    'data',  T2.`data`
                ),
                CONCAT('{"info": ',  T2.`info`, '}')
            )
        ),
        ']}'
    ) AS `elements`,
FROM `table` T1
INNER JOIN `table2` T2
    ON T1.`id` = T2.`fk_t1_id`
GROUP BY T1.`id`


来源:https://stackoverflow.com/questions/45278721/mysql-json-object-with-some-fields-already-containing-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!