Вы находитесь на странице: 1из 23

Query and output JSON data

BootCamp - Batch5
What is JSON?

• JSON stands for JavaScript Object Notation


• JSON is mainly used to store and exchange information
• JSON data is well organized, easy-to-access and in human-readable format of data that can be accessed in a
logical manner
• JSON is self-describing and easy to understand
• JSON is a lightweight data-interchange format
• JSON is language independent
• JSON is used primarily to transmit data between a server and web application, as an alternative to XML

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.

Everything in JSON is stored in the form of a key – value


pairs. As shown in the image,

people is a root object which refers to json of type array


and the “lastname” is a key and the “spachos” is a value.

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

-- Load file contents into a table


SELECT BulkColumn
INTO #temp
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)

WHILE(@i < 10)


BEGIN
SET @file = 'C:\JSON\Books\book' + cast(@i AS VARCHAR(5)) + '.json';
SELECT @json = BulkColumn FROM OPENROWSET (BULK (@file), SINGLE_CLOB) AS j
SELECT * FROM OPENJSON(@json) AS json
-- Optionally, save the JSON text in a table.
SET @i = @i + 1 ;
END 8
Validate, Query, and Change JSON Data
with Built-in Functions

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.

Consider the following json :


DECLARE @jsonInfo NVARCHAR(MAX)

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 JSON_QUERY function extracts an object or an array from a JSON string.

The following example shows how to return a JSON fragment in query results.

SELECT FirstName, LastName, JSON_QUERY(jsonInfo,'$.info.address') AS Address


FROM Person.Person
ORDER BY LastName

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.

Consider the following sample JSON text.


JSON_VALUE ret JSON_QUERY re
Path urns turns
{
"a": "[1,2]", $ NULL or error { "a": "[1,2]",
"b": [1, 2], "b": [1,2],
"c": "hi" "c":"hi"}
}
$.a [1,2] NULL or error

In the above JSON, a and c are $.b NULL or error [1,2]


string values, while b is an array.
$.b[0] 1 NULL or error
The JSON_VALUE and JSON_QUERY
now will output following: $.c hi NULL or error 13
Update property values in JSON text by using the
JSON_MODIFY function

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.

SET @info = JSON_MODIFY(@jsonInfo, "$.info.address[0].town", 'London')

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:

OPENJSON( jsonExpression [ , path ] ) [ <with_clause> ]

<with_clause> ::= WITH ( { colName type [ column_path ] [ AS JSON ] } [ ,...n ] )

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

SELECT * NullValue NULL 0


FROM OPENJSON(@json)
ArrayValue ["a","r","r","a","y"] 4

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"]
}
}
}';

SELECT [key], value


FROM OPENJSON(@json,'$.path.to."sub-object"')

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:

Number Date Customer Quantity Order

SO43659 2011-05- AW29825 1 {"Number"


31T00:00:0 :"SO43659
0 ","Date":"2
011-05-
31T00:00:0
0"}

SO43661 2011-06- AW73565 3 {"Number"


01T00:00:0 :"SO43661
0 ","Date":"2
011-06-
01T00:00:0
0"}

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

Вам также может понравиться