簡體   English   中英

我可以在沒有源列名稱成為 SQL Server 2016 中的鍵的情況下使用 FOR JSON 嗎?

[英]Can I use FOR JSON without a source column name becoming a key in SQL Server 2016?

我有一個表,其中包含帶有組 ID 的 json 字符串。 我想創建一個包含所有具有相同 id 的 json 對象的 json 數組。

請注意,在我的例子中,我試圖放入數組的列內容本身就是 json 片段,因此我的案例和問題比將行轉換為數組更具體。 在接受的答案中使用OPENJSON也利用了這個細節。

但是,我找不到一種使用 FOR JSON 的方法,它允許我選擇一個列,而該列的名稱不會成為數組中所有對象的鍵。

我意識到我試圖擺脫的關鍵是將列投影到 json 的鍵值表示的鍵,但在這種情況下,我只選擇一列,我很好奇是否有我不能的技巧考慮到。

我可以通過簡單地使用 COALASCE 來實現我想要的,但我想知道是否可以使用 FOR JSON 來處理這種邊緣情況。 這是演示我正在嘗試做的事情的簡化代碼:

BEGIN
    declare @Json_Snippets table (id int, json nvarchar(max));

    insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"one"}}');
    insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"two"}}');

   select
          JSON_QUERY(js.json) as 'dont_want_this'
   from
        @Json_Snippets js
    FOR JSON PATH;

END

我必須 JSON_QUERY 以避免轉義 json 列中的字符,即 json 字符串保持為 json。 運行上面給出:

[{"dont_want_this":{"root":{"obj":"one"}}},{"dont_want_this":{"root":{"obj":"two"}}}]

我想得到的是:

[{"root":{"obj":"one"}},{"root":{"obj":"two"}}]

如果我理解正確,下一種方法可能會有所幫助。 只需使用OPENJSON()WITH子句選擇您的json數據,然后使用FOR JSON格式化結果:

-- Table
declare @Json_Snippets table (id int, json nvarchar(max));
insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"one"}}');
insert into @Json_Snippets (id, json) VALUES (1, '{"root":{"obj":"two"}}');

-- Statement
SELECT j.[root]
FROM @Json_Snippets t
CROSS APPLY OPENJSON(t.json, '$') WITH ([root] nvarchar(max) AS JSON) j
FOR JSON AUTO

輸出:

[{"root":{"obj":"one"}},{"root":{"obj":"two"}}]

如果您知道根鍵,則可以使用OPENJSON() WITH (... AS JSON)將它們的值提取為 json 並使用FOR JSON重新創建 json。 這是一個例子:

DECLARE @json_snippets TABLE (id INT, json NVARCHAR(MAX));
INSERT INTO @json_snippets (id, json) VALUES
(1, '{"root":{"obj":"one"}}'),
(1, '{"root":{"obj":"two","foo":"bar"}}'),
(2, '{"root":{"obj":"three"}}');

SELECT id, (
    SELECT j.*
    FROM @json_snippets AS x
    CROSS APPLY OPENJSON(json) WITH (
        root NVARCHAR(MAX) AS JSON
    ) AS j
    WHERE id = t.id
    FOR JSON AUTO
)
FROM @json_snippets AS t
GROUP BY id
DECLARE @json_snippets TABLE (person INT, [json] NVARCHAR(MAX));
INSERT INTO @json_snippets (person, json) VALUES
(1, '{"obj":"one"}'),
(1, '{"obj":"two","foo":"bar"}'),
(2, '{"obj":"three"}');

SELECT x.person, JSON_QUERY('[' +x.sagg + ']') as objs
FROM (
    SELECT  w.person, STRING_AGG ([json], ',') as sagg
    FROM @json_snippets as w
    GROUP BY w.person
) as x
FOR JSON PATH

結果(我在漂亮印刷方面的最佳嘗試):

[
    {"person":1,"objs":[
                 {"obj":"one"}
                 ,{"obj":"two","foo":"bar"}
            ]
    }
    ,{"person":2,"objs":[
                {"obj":"three"}
            ]
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM