防止 SQL 中 FOR JSON 输出中的双重转义 JSON

Prevent double-escaped JSON in FOR JSON output in SQL

我的情况有一个小问题因为在我的情况下,列可以包含文本 'John' 直接或文本作为数组 '["John","Smith" ]' 两个都。那么如何防止 FOR JSON output 中的双重转义 JSON?我想我在这里做错了什么。请检查我的示例:

Create table #jsonTest(NameList varchar(max))
insert into #jsonTest(NameList)
select '["John","Smith"]'

现在,如果我想要它的输出,它将给出正确的输出(没有转义字符):

select JSON_QUERY(NameList) NameList from #jsonTest for json auto

输出:

[{"NameList":["John","Smith"]}]

简单文本示例:

truncate table #jsonTest
insert into #jsonTest(NameList)
Select 'John'

现在对于这个 我必须更改我的 select 查询以获得正确的输出,因为 JSON_QUERY,如前所述,它只有 returns 对象和数组。 所以我把它改成了这样:

select case when ISJSON(NameList) = 1 then JSON_QUERY(NameList) else NameList end NameList from #jsonTest for json auto

输出:

[{"NameList":"John"}]

现在它现在会给出正确的输出但是如果我再次插入以前的数据并尝试上select查询

truncate table #jsonTest
insert into #jsonTest(NameList)
select '["John","Smith"]'

select case when ISJSON(NameList) = 1 then JSON_QUERY(NameList) else NameList end NameList from #jsonTest for json auto

输出:

[{"NameList":"[\"John\",\"Smith\"]"}]

然后它在输出中给出转义字符。代码有什么问题?

此行为在 documentation - If the source data contains special characters, the FOR JSON clause escapes them in the JSON output with '\'. Of course, as you already know, when JSON_QUERY() is used with FOR JSON AUTO 中进行了解释,FOR JSON 不会在 JSON_QUERY return 值 [=29] 中转义特殊字符=].

您的问题在于,您的数据并不总是 JSON。因此,一种可能的方法是生成具有重复列名的语句 (NameList)。默认情况下 FOR JSON AUTO 不在输出中包含 NULL 值,因此结果是预期的 JSON。请注意,您不能在语句中使用 INCLUDE_NULL_VALUES,否则最终的 JSON 将包含重复键。

Table:

CREATE TABLE #jsonTest(NameList varchar(max))
insert into #jsonTest(NameList)
select '["John","Smith"]'
insert into #jsonTest(NameList)
Select 'John'

声明:

SELECT
   JSON_QUERY(CASE WHEN ISJSON(NameList) = 1 THEN JSON_QUERY(NameList) END) AS NameList,
   CASE WHEN ISJSON(NameList) = 0 THEN NameList END AS NameList
FROM #jsonTest 
FOR JSON AUTO

结果:

[{"NameList":["John","Smith"]},{"NameList":"John"}]