Following query returns whole table as single JSON string (list of JSON objects - one per row):
SELECT * FROM MyTable FOR JSON AUTO
I need to return multiple rows where each row will be a JSON string of a signle row of the table.
For example if table fields are A,B,C output should be:
{A: <value>, B: <value>, C: <value>}
{A: <value>, B: <value>, C: <value>}
{A: <value>, B: <value>, C: <value>}
...
{A: <value>, B: <value>, C: <value>}
How to do this in TSQL ?
While it's possible to construct JSON strings by hand by concatenating strings, I'd prefer to reuse existing tool that would handle cases like quotes in values.
You don't need a custom query language to query JSON in SQL Server. To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function.
Format query results as JSON, or export data from SQL Server as JSON, by adding the FOR JSON clause to a SELECT statement.
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is language independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is a very popular data interchange format nowadays. Most modern services return the data into the JSON text.
This will return json data in rows from a select statement.
DECLARE @json NVARCHAR(Max)
SET @json = (SELECT * FROM [Sales].[Customers] FOR JSON PATH, ROOT('data'))
SELECT value
FROM OPENJSON(@json,'$.data');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With