JSON, Please help creating the Json format from a table

PC238 20 Reputation points
2023-05-05T15:28:21.6766667+00:00

Hello Everyone,

In SQL Server 2019 Database, I have a table with columns StudentId, Agreement, StudentName

Please help me with the query which creates below Jason for each record.

{   "SingleValues": [    {     "fieldValue": "No",     "fieldName": "Agreement"    
						 },    
						 {     "fieldValue": "John Doe",     "fieldName": "StudentName"    
						 }   
					]  
}
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,713 questions
{count} votes

1 answer

Sort by: Most helpful
  1. CosmogHong-MSFT 22,941 Reputation points Microsoft Vendor
    2023-05-08T02:42:10.76+00:00

    Hi @PC238

    How about this query?

    CREATE TABLE #TEMP(StudentId INT, Agreement VARCHAR(20), StudentName VARCHAR(20))
    INSERT INTO #TEMP VALUES
    (1,'No','John Doe')
    
    SELECT *,CONCAT('{ "SingleValues": [ { "fieldValue": "'
                   ,Agreement
    			   ,'", "fieldName": "Agreement" },{ "fieldValue": "'
    			   ,StudentName
    			   ,'", "fieldName": "StudentName" } ] }') AS [JSON]
    FROM #TEMP ;
    

    Output:

    User's image

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments