SQL Server 2016 will support JSON (JavaScript Object Notation). JSON is an open, text-based exchange format based on JavaScript’s object literal notation. JSON is a popular data-interchange format used in modern web and mobile applications, as well for storing unstructured data. It is supported in several DB/NoSQL engines and this improvement will enable developers to put some JSON processing logic in the SQL Server that will enable them to parse, query, analyze, and update JSON data.
AdventureWorks Database
In this post, you will query a standard table and then convert it into JSON format. For this example, you are querying the standard AdventureWorks database:
SELECT TOP(2) PP.[PersonType], PP.[FirstName], PP.[MiddleName], PP.[LastName], EA.[EmailAddress] FROM Person.Person PP INNER JOIN [Person].[EmailAddress] EA ON EA.[BusinessEntityID] = PP.[BusinessEntityID]
Sample output for rows inside SQL Server Management Studio looks like below:
JSON AUTO Support
Now, you will add the FOR JSON AUTO support to get the same output in JSON format.
SELECT TOP(2) PP.[PersonType], PP.[FirstName], PP.[MiddleName], PP.[LastName], EA.[EmailAddress] FROM Person.Person PP INNER JOIN [Person].[EmailAddress] EA ON EA.[BusinessEntityID] = PP.[BusinessEntityID] FOR JSON AUTO
The output looks like below:
[ { "PersonType":"EM", "FirstName":"X", "MiddleName":"Y", "LastName":"Z", "EA":[{"EmailAddress":"xyz@test.com"}] }, {"PersonType":"EM", "FirstName":"A", "MiddleName":"B", "LastName":"C", "EA":[{"EmailAddress":"abc@test.com"}] } ]
Generate JSON
You can also generate JSON using the PATH option like:
SELECT TOP(2) PP.[PersonType], PP.[FirstName], PP.[MiddleName], PP.[LastName], EA.[EmailAddress] FROM Person.Person PP INNER JOIN [Person].[EmailAddress] EA ON EA.[BusinessEntityID] = PP.[BusinessEntityID] FOR JSON PATH The output for this query would look little different like: [ {"PersonType":"EM", "FirstName":"X”, “MiddleName":"Y”, “LastName":"Z”, “EmailAddress":"xyz@test.com"},{"PersonType":"EM”, “FirstName":"A”, “MiddleName":"B”, “LastName":"C”, “EmailAddress":"abc@test.com"} ]
Now that you are able to generate few simple output using JSON keyword.
HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.