SQL Server 2016: Built-In JSON Support

JSON stands for JavaScript Object Notation and it is widely used for data representation in the data services world. With JSON support, you can format query results as JSON by adding the FOR JSON clause to a SELECT statement in SQL Server. Also, you can converts JSON data to rows and columns by calling the OPENJSON rowset provider function.

Below we are going to see some examples of utilizing SQL Server's JSON support.

For the purposes of these demos, I have created a sample tabled called "Students" and I have populated it with random data. Let's take a look at the first 10 rows of this table:


























Figure 1: Sample Table "Students".

In order to extract data from a table and represent it in the JSON format you must use wither the "FOR JSON AUTO" clause or the "FOR JSON PATH" clause.

The "FOR JSON AUTO" clause allows you to have full control over the format of the JSON output. For example, you can specify the root.

Example:


Figure 2: Using the "FOR JSON AUTO" Clause.


The "FOR JSON PATH" clause automatically formats the JSON output based on the structure of the source table.

Example:














Figure 3: Using the "FOR JSON PATH" Clause.


Now, if you want to transform JSON data into a tabular form, you can use the OPENJSON rowset function.

Example:





























Figure 4: Using the "OPENJSON" Rowset Function.



References: 
MSDN Library Article: What's New in SQL Server 2016, November Update
MSDN Library Article: Format Query Results as JSON with FOR JSON (SQL Server)
MSDN Library Article: Convert JSON Data to Rows and Columns with OPENJSON (SQL Server)

See also...
SQL Server 2016 Top Features


Labels: , ,