If I have a table with a column containing an arbitrary valid JSON document, can I embed that document into a query returing JSON other than as a string?
For 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 *
FROM #Example
FOR JSON AUTO;
Actual output:
[
{
"Name":"Document 1",
"Document":"{ \"a\": \"a\" }"
},
{
"Name":"Document 2",
"Document":"{ \"b\": \"b\" }"
}
]
Desired output (note that the parsed value of Document
has been embedded):
[
{
"Name":"Document 1",
"Document": { "a": "a" }
},
{
"Name":"Document 2",
"Document": { "b": "b" }
}
]
asked Aug 18, 2022 at 23:42
1 Answer 1
Use JSON_QUERY
with no path to prevent escaping
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;
outputs
[
{
"name":"Document 1",
"Document":{ "a": "a" }
},
{
"name":"Document 2",
"Document":{ "b": "b" }
}
]
Charlieface
17.6k22 silver badges45 bronze badges
answered Aug 19, 2022 at 14:04
David Browne - Microsoft David Browne - Microsoft
49.2k3 gold badges53 silver badges102 bronze badges
lang-sql
JSON_VALUE
doesn't exist in previous versions - though it does refer to this issue. The referencedJSON_VALUE(D.DATA,'$')
does not work, and I can't find any blog referring to that.