JSON查询返回带有转义字符的结果

时间:2018-03-16 16:01:49

标签: json sql-server sql-server-2016 sql-server-json

从以下查询中我得到结果:

"Units": "[{\"Name\":\"Unit25\"}]",

查询是跟随查询再现这个结果,我已经简化了查询实际查询使用但基于选择是这样的:

SELECT (      
SELECT *
  FROM (      
        SELECT
           JSON_QUERY(COALESCE((SELECT [Name] FROM (
                    SELECT [Name] 
                    FROM [TableA]                                                       
                    UNION 

                    SELECT TOP 3 [Name] 
                    FROM [TableB]) [T]
                    FOR JSON PATH),'[]')) AS [Units]
            FROM [User] [U]

               UNION

      SELECT
        JSON_QUERY(COALESCE((SELECT [Name] FROM (
                    SELECT [Name] 
                    FROM [TableA]                                                       
                    UNION 

                    SELECT TOP 3 [Name] 
                    FROM [TableB]) [T]
                    FOR JSON PATH),'[]')) AS [Units]
        FROM [Contact] [C]
         ) [Data] 
    FOR JSON PATH, INCLUDE_NULL_VALUES)

预期结果:

"Units": "[{"Name":"Unit25"}]",

如何实现?

1 个答案:

答案 0 :(得分:0)

这里的问题是在JSON_QUERY语句之前使用UNION会以某种方式破坏json的转义。也许您可以使用JSON_QUERY作为最重要的语句来修正查询:

select JSON_QUERY(units) as Units from
(
    SELECT
        COALESCE((SELECT [Name] FROM (
                SELECT [Name] 
                FROM [TableA]                                                       
                UNION 

                SELECT TOP 3 [Name] 
                FROM [TableB]) [T]
                FOR JSON PATH),'[]')  AS [Units]
        FROM [User] [U]
           UNION
  SELECT
     COALESCE((SELECT [Name] FROM (
                SELECT [Name] 
                FROM [TableA]                                                       
                UNION 

                SELECT TOP 3 [Name] 
                FROM [TableB]) [T]
                FOR JSON PATH),'[]')  AS [Units]
    FROM [Contact] [C]
) u
FOR JSON auto, INCLUDE_NULL_VALUES

结果:

enter image description here