Share via

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 | Other

1 answer

Sort by: Most helpful
  1. LiHongMSFT-4306 31,621 Reputation points
    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.

    Was this answer helpful?

    0 comments No comments

Your answer

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