The JSON In SQL 2016

Abstract

This blog helps to explain the Application of JSON data and use new SQL 2016 constructs that enables an integration of JSON data to a relational schema. The idea behind this article is to list as many examples of JSON nested elements, sample data to be converted to JSON, JSON to the relational data, JSON elements to a separate column and JSON data to the separate rows.

Introduction

JSON stands for JavaScript Object Notation. JSON is the primary data representation for all NoSQL databases.This is a natural fit for the developers, who use JSON as the data interchange format in their Applications. The relative ability of JSON (JSON records are well structured but easily extended) on its scalability has attracted the developers looking DB migrations in agile environments. Data and schema, in volume, can be hard to change. Rewriting a large dataset stored on the disk while keeping the associated Applications online can be time-consuming. It can take days of background processing, in moderate to large examples, to upgrade the data

Background

Most of the traditional relational database engine now supports JSON. With SQL Server 2016, It's easy to interchange JSON data between the Applications and database engine. Microsoft has provided various functions and capabilities to parse JSON data. They tried to bring JSON data into a relational storage. It also provides an ability to transform the relational data into JSON and JSON data into the denormalized data.

Having these additional JSON features built into SQL Server should make it easier for the Applications to exchange JSON data witth SQL Server.This functionality provides the flexibility in the integration of JSON data into the relational database engine. The developers can write and invent complex queries during their periodic stages of the development process.

Relational databases refers to the traditional data storage, Constructive and Intuitive SQL language, Complex query design and ACID property. NoSQL offers different concepts - complex structures are placed together into the collections of the entities, where you can take everything, which you need with one read operation or where you can insert complex structure with a single write and follows CAP property.

The relational databases normalize the data to some degree; that is, rather than repeating a piece of data in multiple rows, a table that needs that information will store a foreign key, which points to another table that holds the data. On the other hand, this process means that the data is typically shredded from its original form to fit into tables and then reassemble at the run time by joining the tables in response to a query. This becomes particularly expensive as the data set grows and the data need to be partitioned among the multiple database servers.

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax.

  • Data is in the name/value pairs.
    {"key""value"} – most common format for objects

  • Data is separated by commas.
    {"key""value"},{"key""value"}

  • Curly braces holds the objects.
    {"key"{"key""value"}}

  • Square brackets holds the arrays.
    {"key"[ {"key""value"},{"key""value"} ]}

JSON Values

In JSON, values must be one of the data types given below.

  • A string
  • A number
  • An object (JSON object)
  • an array
  • A boolean
  • null

Basic Structure

If you have parent/child (Fact/Dimension) relationships, where related child information is not changed frequently and you need to read the child records together with the parent without the additional JOINS, you can store the child records in the parent table as JSON array.

In the traditional database, normalization process ensures to minimize the amount of information that duplicates but whereas in NoSQL, intentionally duplicate it to make it easier to use. Let's say, representing a number of students taking a class. A normalized way of representing the data is given below. The use of an array denotes the dimension data of the relational table

  1. {  
  2.     course "Basic programming",  
  3.         room "1A",  
  4.         students[{  
  5.             id 1,  
  6.             name "Prashanth"  
  7.         }, {  
  8.             id 2,  
  9.             name "Jayaram"  
  10.         }]  
  11. }  
Here's a denormalized data.
  1. [{  
  2.     course "Basic programming",  
  3.     room "1A",  
  4.     studentId 1,  
  5.     studentName "Prashanth"  
  6. }, {  
  7.     course "Basic programming",  
  8.     room "1A",  
  9.     studentId 2,  
  10.     studentName "Jayaram"  
  11. }]  
When you parse the JSON container, you will end up in fetching the denormalized data in one table.

Let's discuss the different dimensions of the sample data given below and represent the data in tabular and JSON file format. Also, you will learn to know how to query JSON file with the various available JSON constructs in SQL 2016

Native JSON support in SQL Server 2016 provides you few functions to read and parse your JSON string into a relational format.
  1. OPENJSON() - Table valued function parses JSON text and returns row set view of JSON.
  2. JSON_Value() - Scalar function returns a value from JSON on the specified path.

The sample output given below is an example of how to demonstrate the different dimension of representing the data into a JSON and the relational data. The example lists parent and child relationship and it is represented in JSON array (batter and topping) and nested objects as well. 

output

output

Transform sample data given above to JSON

  1. [{  
  2.     "id""0001",  
  3.     "type""donut",  
  4.     "name""Cake",  
  5.     "ppu": 0.55,  
  6.     "batters": {  
  7.         "batter": [{  
  8.             "id1""1001",  
  9.             "type1""Regular"  
  10.         }, {  
  11.             "id1""1002",  
  12.             "type1""Chocolate"  
  13.         }, {  
  14.             "id1""1003",  
  15.             "type1""Blueberry"  
  16.         }, {  
  17.             "id1""1004",  
  18.             "type1""Devils Food"  
  19.         }]  
  20.     },  
  21.     "topping": [{  
  22.         "id2""5001",  
  23.         "type2""None"  
  24.     }, {  
  25.         "id2""5002",  
  26.         "type2""Glazed"  
  27.     }, {  
  28.         "id2""5005",  
  29.         "type2""Sugar"  
  30.     }, {  
  31.         "id2""5007",  
  32.         "type2""Powdered Sugar"  
  33.     }, {  
  34.         "id2""5006",  
  35.         "type2""Chocolate with Sprinkles"  
  36.     }, {  
  37.         "id2""5003",  
  38.         "type2""Chocolate"  
  39.     }, {  
  40.         "id2""5004",  
  41.         "type2""Maple"  
  42.     }]  
  43. }, {  
  44.     "id""0002",  
  45.     "type""donut",  
  46.     "name""cup Cake",  
  47.     "ppu": 0.5,  
  48.     "batters": {  
  49.         "batter": [{  
  50.             "id1""1001",  
  51.             "type1""Regular"  
  52.         }, {  
  53.             "id1""1002",  
  54.             "type1""Chocolate"  
  55.         }, {  
  56.             "id1""1003",  
  57.             "type1""Blueberry"  
  58.         }, {  
  59.             "id1""1004",  
  60.             "type1""Devil's Food"  
  61.         }]  
  62.     },  
  63.     "topping": [{  
  64.         "id2""5001",  
  65.         "type2""None"  
  66.     }, {  
  67.         "id2""5002",  
  68.         "type2""Glazed"  
  69.     }, {  
  70.         "id2""5005",  
  71.         "type2""Sugar"  
  72.     }]  
  73. }]  
output

Transform JSON to Relational data

OPENJSON is a table-value function (TVF). which looks into JSON text, locates an array of JSON objects, iterates through the elements of the array and for each element returns one row in the output result.

To read JSON from the file, load the file using OPENROWSET construct into a variable. The stocks.json is an example for the demonstration. You can derive the path as per your requirement and the environment.

In the following example is shown SQL code, which reads the content of the JSON file, using OPENROWSET BULK function and passes the content of JSON file (BulkColumn) to OPENJSON function

JSON file can be stored in local file system or global (Cloud storage).
  1. SELECT ID, type, name, ppu, type1 batter, type2 topping FROM  
  2. OPENROWSET(BULK N '\\hq6021\c$\stocks.json', SINGLE_CLOB) AS json  
  3. CROSS APPLY OPENJSON(BulkColumn)  
  4. WITH(id nvarchar(40), type nvarchar(40), name NVARCHAR(MAX), ppu NVARCHAR(MAX), batters NVARCHAR(MAX) AS JSON, topping NVARCHAR(MAX) AS JSON) AS t  
  5. CROSS APPLY  
  6. OPENJSON(batters, '$.batter')  
  7. WITH(id1 nvarchar(100), type1 nvarchar(20))  
  8. CROSS APPLY  
  9. OPENJSON(topping)  
  10. WITH(id2 nvarchar(100), type2 nvarchar(20))  
output

Built-in functions for JSON processing

SQL Server 2016 provides the functions for parsing and processing JSON text. JSON built-in functions, which are available in SQL Server 2016 are given below.
  • ISJSON( jsonText ) checks, if the NVARCHAR text is properly formatted according to the JSON specification. You can use this function to create check constraints on NVARCHAR columns, which contains JSON text
  • JSON_VALUE( jsonText, path ) parses jsonText and extracts the scalar values on the specified JavaScript-like path (see below for some JSON path examples).
  • JSON_QUERY( jsonText, path ) that parses jsonText and extracts objects or arrays on the specified JavaScript-like path (see below for some JSON path examples)
These functions use JSON paths for referencing the values or objects in JSON text. JSON paths use JavaScript-like syntax for referencing the properties in JSON text. Some examples are given below.
  • '$' – references entire JSON object in the input text.
  • '$.property1' – references property1 in JSON object.
  • '$[4]' – references 5-th element in JSON array (indexes are counted from 0 like in JavaScript).
  • '$.property1.property2.array1[5].property3.array2[15].property4' – references complex nested property in the JSON object.
  • '$.info. "first name"' – references "first name" property in info object. If key contains some special characters such as space, dollar, etc., it should be surrounded with double quotes.

Dollar sign ($) represents the input JSON object (similar to root “/” in XPath language). You can add any JavaScript-like property or an array after “$” to reference properties in JSON object. One simple example of a query, where these built-in functions are used are given below.

  1. DECLARE @MyJSON NVARCHAR(4000) = N '{   
  2. "info" {  
  3.     "type"  
  4.     1, "address" {  
  5.         "town"  
  6.         "Louisville""county"  
  7.         "Boulder""country"  
  8.         "USA"  
  9.     }, "tags" ["Snow""Breweries"]  
  10. }, "LocationType"  
  11. "East""WeatherType"  
  12. "Cold"  
  13. }  
  14. '   
  15. Select * from OPENJSON(@MyJSON)  
  16. WITH(type int '$.info.type', LocationType varchar(20)  
  17.     '$.LocationType', WeatherType varchar(20)  
  18.     '$.WeatherType', town varchar(200)  
  19.     '$.info.address.town', county varchar(200)  
  20.     '$.info.address.county', country varchar(200)  
  21.     '$.info.address.country') AS t  
  22. CROSS APPLY  
  23. OPENJSON(@MyJSON, '$.info.tags')  
BlogImages

How to define Nested Objects in JSON

The examples given above also contains a sample data that represents nested object.
  1. DECLARE @json NVARCHAR(1000)  
  2. SELECT @json = N '{   
  3. "Employee" [{  
  4.     "Element"  
  5.     1  
  6. }, {  
  7.     "Element"  
  8.     2  
  9. }, {  
  10.     "Element"  
  11.     "n"  
  12. }]  
  13. }  
  14. '  
Parsing Nested elements of JSON

In the employee example given below, the employeeDepartment is the root of the JSON. The array element DEPT has a dimension data, which represents the department details of each employee. The employee JSON structure has 3 objects.
  1. DECLARE @MyJSON NVARCHAR(4000) = N '{    
  2. "EmployeeDepartment": [{  
  3.     "EmployeeID""E0001",  
  4.     "FirstName""Prashanth",  
  5.     "LastName""Jayaram",  
  6.     "DOB""1983-02-03",  
  7.     "DEPT": [{  
  8.         "EmployeeDepartment""Ducks"  
  9.     }, {  
  10.         "EmployeeDepartment""Blues"  
  11.     }]  
  12. }, {  
  13.     "EmployeeID""E0002",  
  14.     "FirstName""Prarthana",  
  15.     "LastName""Prashanth",  
  16.     "DOB""2015-07-06",  
  17.     "DEPT": [{  
  18.         "EmployeeDepartment""Red Wings"  
  19.     }]  
  20. }, {  
  21.     "EmployeeID""E0003",  
  22.     "FirstName""Pravitha",  
  23.     "LastName""Prashanth",  
  24.     "DOB""2015-07-06",  
  25.     "DEPT": [{  
  26.         "EmployeeDepartment""Red Wings"  
  27.     }, {  
  28.         "EmployeeDepartment""Green Bird"  
  29.     }]  
  30. }]  
  31. }  
  32. '    
  33. --SELECT * FROM OPENJSON(@MyJSON)  
  34. SELECT  
  35. EmployeeID,  
  36. FirstName,  
  37. LastName,  
  38. DOB,  
  39. DEPT,  
  40. EmployeeDepartment  
  41. FROM OPENJSON(@MyJSON, '$.EmployeeDepartment')  
  42. WITH(EmployeeID varchar(10), FirstName varchar(25), LastName varchar(25), DOB varchar(25), DEPT NVARCHAR(MAX) AS JSON) AS E  
  43. CROSS APPLY  
  44. OPENJSON(DEPT)  
  45. WITH(EmployeeDepartment nvarchar(100))  
BlogImages

Reading JSON into separate rows

How about pulling them in separate rows, using JSON_Value() with OPENJSON() function. The query given below gives an overview of applying the JSON constructs on the nested elements.
  1. DECLARE @MyJSON NVARCHAR(4000) = N '{    
  2. "EmployeeDepartment": [{  
  3.     "EmployeeID""E0001",  
  4.     "FirstName""Prashanth",  
  5.     "LastName""Jayaram",  
  6.     "DOB""1983-02-03",  
  7.     "DEPT": [{  
  8.         "DeptID""D1",  
  9.         "DName""Ducks"  
  10.     }, {  
  11.         "DeptID""D2",  
  12.         "DName""Blues"  
  13.     }]  
  14. }, {  
  15.     "EmployeeID""E0002",  
  16.     "FirstName""Prarthana",  
  17.     "LastName""Prashanth",  
  18.     "DOB""2015-07-06",  
  19.     "DEPT": [{  
  20.         "DeptID""D3",  
  21.         "DName""Red Wings"  
  22.     }]  
  23. }, {  
  24.     "EmployeeID""E0003",  
  25.     "FirstName""Pravitha",  
  26.     "LastName""Prashanth",  
  27.     "DOB""2015-07-06",  
  28.     "DEPT": [{  
  29.         "DeptID""D3",  
  30.         "DName""Red Wings"  
  31.     }, {  
  32.         "DeptID""D4",  
  33.         "DName""Green Bird"  
  34.     }]  
  35. }]  
  36. }  
  37. '    
  38. SELECT  
  39. JSON_Value(c.value, '$.EmployeeID') as EmployeeID,  
  40.     JSON_Value(c.value, '$.FirstName') as FirstName,  
  41.     JSON_Value(C.value, '$.DOB') as DOB,  
  42.     JSON_Value(p.value, '$.DeptID') as DEPTID,  
  43.     JSON_Value(p.value, '$.DName') as DName  
  44. FROM OPENJSON(@MyJSON, '$.EmployeeDepartment') as c  
  45. CROSS APPLY OPENJSON(c.value, '$.DEPT') as p  
BlogImages

Reading JSON elements into separate columns

You can specify the child elements with the full path by using the dollar sign “$” inside the WITH() clause to segregate the data into the separate columns.
  1. DECLARE @MyJSON NVARCHAR(4000) = N '{    
  2. "EmployeeDepartment": [{  
  3.     "EmployeeID""E0001",  
  4.     "FirstName""Prashanth",  
  5.     "LastName""Jayaram",  
  6.     "DOB""1983-02-03",  
  7.     "DEPT": [{  
  8.         "DeptID""D1",  
  9.         "DName""Ducks"  
  10.     }, {  
  11.         "DeptID""D2",  
  12.         "DName""Blues"  
  13.     }]  
  14. }, {  
  15.     "EmployeeID""E0002",  
  16.     "FirstName""Prarthana",  
  17.     "LastName""Prashanth",  
  18.     "DOB""2015-07-06",  
  19.     "DEPT": [{  
  20.         "DeptID""D3",  
  21.         "DName""Red Wings"  
  22.     }]  
  23. }, {  
  24.     "EmployeeID""E0003",  
  25.     "FirstName""Pravitha",  
  26.     "LastName""Prashanth",  
  27.     "DOB""2015-07-06",  
  28.     "DEPT": [{  
  29.         "DeptID""D3",  
  30.         "DName""Red Wings"  
  31.     }, {  
  32.         "DeptID""D4",  
  33.         "DName""Green Bird"  
  34.     }]  
  35. }]  
  36. }  
  37. '    
  38. SELECT  
  39. EmployeeID,  
  40. FirstName,  
  41. DOB,  
  42. Dept1, DName1,  
  43. Dept2, DName2  
  44. FROM OPENJSON(@MyJSON, '$.EmployeeDepartment')  
  45. WITH(EmployeeID varchar(20)  
  46.     '$.EmployeeID', FirstName varchar(20)  
  47.     '$.FirstName', DOB varchar(20)  
  48.     '$.DOB', Dept1 varchar(20)  
  49.     '$.DEPT[0].DeptID', Dname1 varchar(20)  
  50.     '$.DEPT[0].DName', Dept2 varchar(20)  
  51.     '$.DEPT[1].DeptID', Dname2 varchar(20)  
  52.     '$.DEPT[1].DName') AS EMP  
BlogImages

Conclusion

SQL 2016 contains some very powerful JSON constructs. Mixing the power of the relational databases with the flexibility of JSON offers many benefits from the point of Migration, Integration, and Deployment.
The powerful JSON SQL constructs enable to query and analyze JSON data as well as transform JSON to the relational data and the relational data to JSON.

There are plenty of examples and resources, which are available under various links. This is an effort to combine real-world scenarios and details the various ways of JSON data manipulation, using SQL 2016 JSON constructs.
NoSQL offers different concepts - complex structures are placed together into the collections of the entities, where you can take everything, which you need with one read operation or where you can insert complex structure with a single write. The bad side is that sometimes you want to organize your information in different collections and then you will find that it is very hard to JOIN entities from the two collections.

With new SQL server, you have options to choose between these two concepts and use the best of both worlds. In your data models, you can choose when to use traditional relational structures and when to introduce NoSQL concepts.

References
  • https//blogs.technet.microsoft.com/dataplatforminsider/2016/01/06/json-in-sql-server-2016-part-2-of-4/
  • https//adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html
  • http//www.w3schools.com/js/js_json_syntax.asp
  • https//www.codeproject.com/Articles/1046120/Friday-the-th-JSON-is-coming-to-SQL-Server