Академический Документы
Профессиональный Документы
Культура Документы
BootCamp - Batch5
What is JSON?
2
Simple JSON format
Generally, a json file is self – describing. Just on seeing the it
will give us the intuition that the format anyone can be
interpreted.
3
Why JSON in SQL Server
Most of the major databases are adopting JSON support because the usage of JSON in Web APIs has increased
significantly
There is a requirement to extract data, which is stored in one database (D1) and load it into another database
(D2). That should be simple, right? But, the client is not ready to give access to the D2 database due to
confidential data.
We have to push data to the D2 database via the REST API which accepts JSON as an input.
We are trying to find an option to convert the data into JSON format at the database level. Unfortunately, SQL
Server does not support converting data into JSON format. To resolve this issue, we developed a .NET utility to
convert the data to JSON format with the help of the “JavaScriptSerializer” class then pushed the data to the D2
database via REST API
I see SQL Server 2016 now supports JSON. Is it possible to replace our .NET utility? In this tip, we will
demonstrate how use JSON in SQL Server 2016.
4
Importing JSON Documents in SQL SERVER
5
Import JSON document into Single Column
• OPENROWSET(BULK) is a table-valued function that can read data from any file on the local drive or network,
if SQL Server has read access to that location.
Here's an example of the OPENROWSET(BULK) function that reads the contents of a JSON file and returns it
to the user as a single value:
Example:
SELECT BulkColumn
FROM OPENROWSET (BULK 'C:\JSON\Books\book.json', SINGLE_CLOB) as j
6
Importing JSON document into local variable and table
We can also load the JSON document in to a single variable in the following way:
-- Load file contents into a variable
SELECT @json = BulkColumn
FROM OPENROWSET (BULK 'C:\JSON\Books\book.json', SINGLE_CLOB) as j
7
Importing Multiple JSON Documents
You can use the same approach to load a set of JSON files from the file system into a local variable one at a time.
DECLARE @i INT = 1
DECLARE @json AS NVARCHAR(MAX)
9
Built – in functions for JSON
ISJSON:
This function checks whether the string contains valid JSON .
EXAMPLE:
SELECT id, json_col
FROM tab1
WHERE ISJSON(json_col) > 0
The above query returns rows in which json_col contain valid JSON.
10
Extract a value from JSON text by using the
JSON_VALUE function
JSON_VALUE:
The JSON_VALUE function extracts a scalar value from JSON string.
SET @jsonInfo=N'{
"info":{
"type":1,
"address":{
"town":"Bristol",
"county":"Avon",
"country":"England"
},
"tags":["Sport", "Water polo"]
},
"type":"Basic"
}' 11
Contd…
The following example extracts the value of the nested json property town into a local variable:
SET @town = JSON_VALUE(@jsonInfo, '$.info.address.town')
JSON_QUERY:
The following example shows how to return a JSON fragment in query results.
12
Compare JSON_VALUE and JSON_Query:
The key difference between JSON_VALUE and JSON_QUERY is that JSON_VALUE returns a scalar value,
while JSON_QUERY returns an object or an array.
The JSON_MODIFY function updates the value of a property in a JSON string and returns the updated JSON
string.
The following example updates the value of a JSON property in a variable that contains JSON.
14
OPEN JSON
OPENJSON is a table-valued function that parses JSON text and returns objects and properties from the JSON
input as rows and columns. In other words, OPENJSON provides a rowset view over a JSON document.
Syntax:
15
Contd…..
EXAMPLE:
Results:
DECLARE @json NVARCHAR(4000) = N'{
key value type
"StringValue":"John",
"IntValue":45, StringValue John 1
"TrueValue":true,
"FalseValue":false, IntValue 45 2
"NullValue":null,
"ArrayValue":["a","r","r","a","y"], TrueValue true 3
"ObjectValue":{"obj":"ect"}
}' FalseValue false 3
ObjectValue {"obj":"ect"} 5
16
Contd…
• Is an optional JSON path expression that references an object or an array
within jsonExpression. OPENJSON seeks into the JSON text at the specified position and parses only the
referenced fragment.
The following example returns a nested object by specifying the path:
DECLARE @json NVARCHAR(4000) = N'{
"path": {
"to":{
"sub-object":["en-GB", "en-UK","de-AT","es-AR","sr-Cyrl"]
}
}
}';
17
Contd…
Results:
Key Value
0 en-GB
1 en-UK
2 de-AT
3 es-AR
4 sr-Cyrl
18
Contd…
DECLARE @json NVARCHAR(MAX) = N'[
{
"Order": {
"Number":"SO43659",
"Date":"2011-05-31T00:00:00"
}
]
SELECT * FROM
OPENJSON ( @json )
WITH (
Number varchar(200) '$.Order.Number',
Date datetime '$.Order.Date',
Customer varchar(200) '$.AccountNumber',
Quantity int '$.Item.Quantity', [Order] nvarchar(MAX) AS JSON
)
19
Contd…
Result:
20
For JSON
The FOR JSON PATH clause uses the column alias or column name to determine the key name in the JSON
output. If an alias contains dots, the PATH option creates nested objects.
Query: Output:
[{
SELECT TOP 5 "Id": 1,
BusinessEntityID As Id, "FirstName": "Ken",
FirstName, LastName, "LastName": "Sanchez",
Title As 'Info.Title', "Info": {
MiddleName As 'Info.MiddleName' "MiddleName": "J"
FROM Person.Person }
FOR JSON PATH }, {
"Id": 2,
"FirstName": "Terri",
"LastName": "Duffy",
"Info": {
"MiddleName": "Lee"
}
21
For JSON AUTO mode
When you specify the AUTO option, the format of the JSON output is automatically determined based on the
order of columns in the SELECT list and their source tables
Query:
Json output:
SELECT TOP 5
[{
BusinessEntityID As Id,
"Id": 1,
FirstName, LastName,
"FirstName": "Ken",
Title As 'Info.Title',
"LastName": "Sánchez",
MiddleName As 'Info.MiddleName'
"Info.MiddleName": "J"
FROM Person.Person
}, {
FOR JSON AUTO
"Id": 2,
"FirstName": "Terri",
"LastName": "Duffy",
"Info.MiddleName": "Lee"
}
22
Discussion