Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SERVER: Export Query RESULT as JSON Object

I am using Azure sql server and trying to export results of a query in the following format.

Required Query Result:

{ "results": [{...},{...}], "response": 0 }

From this example : https://msdn.microsoft.com/en-us/library/dn921894.aspx

I am using this sql but I am not sure how to add another response property as a sibling to the root property :"results".

Current Query:

SELECT name, surname
FROM emp
FOR JSON AUTO, ROOT('results')

Output of Query:

{ "results": [ { "name": "John", "surname": "Doe" }, { "name": "Jane", "surname": "Doe" } ] }

like image 324
Basit Munir Avatar asked Jul 03 '26 08:07

Basit Munir


2 Answers

Use FOR JSON PATH instead of FOR JSON AUTO. See the Format Query Results as JSON with FOR JSON (SQL Server) page for several examples, including dot-separated column names and queries from SELECTS

like image 69
Andrew Loree Avatar answered Jul 05 '26 20:07

Andrew Loree


There is no built-in option for this format, so maybe the easiest way would be to manually format response, something like:

declare @resp nvarchar(20) = '20'
SELECT '{"response":"' +
         (SELECT * FROM emp FOR JSON PATH) +
         '", "response": ' + @resp + ' }' 

FOR JSON will do harder part (formatting table) and you just need to wrap it.

like image 37
Jovan MSFT Avatar answered Jul 05 '26 22:07

Jovan MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!