Tsql to generate json array

CzarR 316 Reputation points
2021-09-02T22:25:05.113+00:00

I am trying to generate json output from a sql table. Need help with the SQL statement please. "schemas" output is not coming as I expected. My sql query is returning extra '\'. Screenshot I indicated how my query should return the output as an array. Need help with fixing my select statement.

Thanks in advance.

Drop TABLE #tmp  
CREATE TABLE #tmp (  
    [EmployeeEmailAccount] [nvarchar](50) NULL,  
    [displayName] [nvarchar](50) NULL  
) ON [PRIMARY]  
GO  
INSERT #tmp ([EmployeeEmailAccount], [displayName]) VALUES (N'******@gmail.com', N'testusr1')  
GO   


SELECT TOP 1     
 [schemas]    = '["urn:scim:schemas:core:2.0:User" , "urn:scim:schemas:extension:fa:2.0:faUser"]',  
 EmployeeEmailAccount as 'userName'  
   FROM #tmp  
   FOR JSON PATH, WITHOUT_ARRAY_WRAPPER  

128796-capture.png

Developer technologies Transact-SQL
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. stone z 76 Reputation points
    2021-09-03T02:12:07.74+00:00

    [schemas] = '[''urn:scim:schemas:core:2.0:User'' , ''urn:scim:schemas:extension:fa:2.0:faUser'']'

    0 comments No comments

  2. EchoLiu-MSFT 14,621 Reputation points
    2021-09-03T05:48:24.883+00:00

    Try:

    SELECT TOP 1   
      [schemas] = '[''urn:scim:schemas:core:2.0:User'' , ''urn:scim:schemas:extension:fa:2.0:faUser'']',
      EmployeeEmailAccount as 'userName'
    FROM #tmp
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    

    Output:

    {"schemas":"['urn:scim:schemas:core:2.0:User' ,
    'urn:scim:schemas:extension:fa:2.0:faUser']",
    "userName":"******@gmail.com"}
    

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  3. Viorel 122.5K Reputation points
    2021-09-03T08:15:39.273+00:00

    To output an array without the unneeded ' and ", try this query too:

    SELECT TOP 1   
        [schemas]    = json_query('["urn:scim:schemas:core:2.0:User" , "urn:scim:schemas:extension:fa:2.0:faUser"]'),
        EmployeeEmailAccount as 'userName'
    FROM #tmp
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.