Monday, December 14, 2015

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.


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.


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.


Figure 4: Using the "OPENJSON" Rowset Function.

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

Check out my latest eBook on SQL Server:
Tuning SQL Server - Ebook

Easily secure your SQL Server instances! Try out DBA Security Advisor!
DBA Security Advisor for SQL Server by SQLArtBits
DBA Security Advisor was developed by SQLArtBits. The tool was being carefully developed for an entire year and it contains comprehensive security checks and recommendations based on proven SQL Server security best practices. Feel free to download and use the Community Edition which is free and if you find it useful, you can consider upgrading to the Enterprise Edition!

Artemakis Artemiou [MVP]

Author & Editor

Artemakis Artemiou is a Senior SQL Server Architect, Software Developer and Microsoft Data Platform MVP. He is also an author, regular blogger, president of Cyprus.NET User Group and CY Country leader of INETA-EU. He is also the creator of DBA Security Advisor and In-Memory OLTP Simulator. Artemakis is a frequent guest author of worldwide well-respected online journals where he writes articles focusing on many SQL Server topics.

Reference: The SQL Server and .NET Hub (