Sql-Server

在 FOR JSON AUTO 中嵌入包含 JSON 的列

  • August 21, 2022

如果我有一個包含任意有效 JSON 文件的列的表,我可以將該文件嵌入到返回 JSON 的查詢中,而不是作為字元串?

例如:

CREATE TABLE #Example (Name nvarchar(50) not null, Document nvarchar(max) not null);

INSERT INTO #Example VALUES 
   ('Document 1', '{ "a": "a" }'),
   ('Document 2', '{ "b": "b" }');

SELECT *
FROM #Example
FOR JSON AUTO;

實際輸出:

[
   {
       "Name":"Document 1",
       "Document":"{ \"a\": \"a\" }"
   },
   {
       "Name":"Document 2",
       "Document":"{ \"b\": \"b\" }"
   }
]

期望的輸出(注意解析後的值Document已經嵌入):

[
   {
       "Name":"Document 1",
       "Document": { "a": "a" }
   },
   {
       "Name":"Document 2",
       "Document": { "b": "b" }
   }
]

使用JSON_QUERY無路徑防止逃逸

drop table if exists #Example
CREATE TABLE #Example (Name nvarchar(50) not null, Document nvarchar(max) not null);

INSERT INTO #Example VALUES 
   ('Document 1', '{ "a": "a" }'),
   ('Document 2', '{ "b": "b" }');

SELECT name, JSON_QUERY(Document) Document
FROM #Example
FOR JSON AUTO;

輸出

[
 {
   "name":"Document 1",
   "Document":{ "a": "a" }
 },
 {
   "name":"Document 2",
   "Document":{ "b": "b" }
 }
]

引用自:https://dba.stackexchange.com/questions/315802