SQL FOR JSON-添加其他数组括号

时间:2018-06-20 14:51:13

标签: sql json sql-server

我一直在寻找以下问题的答案。 如何在子选择中添加一个额外的数组括号?

我有以下查询:

select 
    -- Images
    (
        SELECT  tMedien.WebshopID   AS 'mediaId',
                (   SELECT  Farbe   AS 'name'
                    FROM    tMedien tOptions
                    WHERE   tOptions.ID = tMedien.ID
                    FOR JSON PATH
                )                   AS 'options'
        FROM    tMedien
        WHERE   tMedien.Hauptartikelnummer  = tHauptartikel.Hauptartikelnummer
        ORDER BY Position
        FOR JSON auto
    )                                                           AS 'images'
FROM        v2Artikelstamm tHauptartikel    
WHERE       Artikelnummer = 'XXXX'
FOR JSON PATH

输出:

[{"images":[{"mediaId":187,"options":[{"name":"904"}]},{"mediaId":188,"options":[{"name":"910"}]},{"mediaId":189,"options":[{"name":"971"}]},{"mediaId":190,"options":[{"name":"982"}]},{"mediaId":191,"options":[{"name":"A94"}]},{"mediaId":192,"options":[{"name":"A95"}]}]}]

但是对于shopware rest api,我需要执行以下操作才能成功分配图片:(“选项”:[[]

[{"images":[{"mediaId":187,"options":[[{"name":"904"}]]},{"mediaId":188,"options":[[{"name":"910"}]]},{"mediaId":189,"options":[[{"name":"971"}]]},{"mediaId":190,"options":[[{"name":"982"}]]},{"mediaId":191,"options":[[{"name":"A94"}]]},{"mediaId":192,"options":[[{"name":"A95"}]]}]}]

我该如何查询?

谢谢。

BR多米尼克

1 个答案:

答案 0 :(得分:0)

谢谢您的评论,我尝试过,它解决了我的问题。 :)

这是必需的查询:

SELECT
    -- Images
    (
        SELECT  tMedien.WebshopID   AS 'mediaId',
                JSON_QUERY('[' + 
                (   SELECT  Farbe   AS 'name'
                    FROM    tMedien tOptions
                    WHERE   tOptions.ID = tMedien.ID
                    FOR JSON PATH
                ) + ']')            AS 'options'
        FROM    tMedien
        WHERE   tMedien.Hauptartikelnummer  = tHauptartikel.Hauptartikelnummer
        ORDER BY Position
        FOR JSON auto
    )                                                           AS 'images'

FROM        v2Artikelstamm tHauptartikel    
WHERE       Artikelnummer = 'BR2000060'
FOR JSON PATH