Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert rows to JSON in TSQL select query?

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.

like image 844
Bohdan Avatar asked Oct 18 '17 02:10

Bohdan


People also ask

Can you query JSON in SQL?

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.

Which of the following clause can format any result set returned by SQL query as JSON text?

Format query results as JSON, or export data from SQL Server as JSON, by adding the FOR JSON clause to a SELECT statement.

What is JSON format in SQL?

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.


1 Answers

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');
like image 173
Jason Byrd Avatar answered Sep 22 '22 09:09

Jason Byrd