Skip to content
Advertisement

Building and Grouping JSON Object in SQL Server

I have the following table and I’m trying to combine the rows into JSON objects.

Username AccessKeys Marker
user1 {"Account":"1","Checking":"0001","Loan":"null","Savings":0} New
user2 {"Account":"2","Checking":"0001","Loan":"null","Savings":0} New
user2 {"Account":"3","Checking":"0001","Loan":"null","Savings":0} New

The result should look something like this.

Username JSON
user1 {"Accounts": [{"Account": "1","Checking": "0001","Loan": null,"Savings": 0}],"Marker": "New"}
user2 {"Accounts": [{"Account": "1","Checking": "0001","Loan": null,"Savings": 0},{"Account": "2","Checking": "0001","Loan": null,"Savings": 0}],"Marker": "New"}

My current query is this. I’ve been able to get this far but not sure how to proceed from here.

Thanks in advance!

Solution

This is my final query.

Advertisement

Answer

With SQL Server creating JSON array elements usually involves json_query, such as…

Which yields the results…

Username JSON
user1 {“Accounts”:[{“Account”:”1″,”Checking”:”0001″,”Loan”:”null”,”Savings”:0}],”Marker”:”New”}
user2 {“Accounts”:[{“Account”:”2″,”Checking”:”0001″,”Loan”:”null”,”Savings”:0},{“Account”:”3″,”Checking”:”0001″,”Loan”:”null”,”Savings”:0}],”Marker”:”New”}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement