I have heard a lot about JSON data format for exchanging data between applications. Please present a quick overview of what is JSON as an introduction to a set of examples showing how I can open JSON data in SQL Server with T-SQL.
Json data format (Java Script Object Notation) is a popular open file format for exchanging data between applications as well as receiving data from a server. There are tens of thousands of live and archived data sources available in JSON format. Around the time this tip is being prepared, Data.gov offered over 146,000 data sources available for download in JSON format. In addition, MSSQLTips.com has several prior tutorials on different ways of handling JSON formatted data with SQL Server relational databases .
This tip especially targets T-SQL analysts who need to ramp up to speed quickly and easily for displaying and importing JSON formatted data into SQL Server. The T-SQL code samples in this tip illustrate ways of displaying JSON formatted data in SQL Server as if they were from a SQL Server database table as well as how to transfer JSON formatted data to SQL Server tables.
While JSON is native to JavaScript, the JSON data format is widely used for exchanging data between any pair of applications – neither of which need to include JavaScript. Another common JSON use case is to store data on a server for download to client applications. You can think of a JSON data object as roughly analogous in purpose to a SQL Server table.
The JSON format is exclusively text based. If an object, such as a song or a painting, cannot be represented in text, then it cannot be within JSON document. However, at least one popular game application designates text values for different sounds within its JSON component. Similarly, an element within JSON document can point at a web page having an internet image file type, such as .jpg or .png.
Many database professionals prefer using JSON to XML for representing and exchanging data because JSON is perceived to be a simpler, lighter weight data storage format. XML documents for representing data require tags. The tags add to the weight (length) of a document representing an object. These tags can add to the length and transfer time of data across the world wide web. Also, there can be custom rules (XSDs) surrounding the interpretation of the tags in an XML document. The XSDs for XML documents add to the complexity of serializing and deserializing text into a data object within an application.
Perhaps the most distinctive JSON feature is that data is stored in key-value pairs. Each distinct key within the set of key-value pairs in some JSON formatted text is roughly analogous to a column in a SQL Server table. A key name instance must appear in double quotes. A colon delimiter (:) separates the key name from the JSON value. The value for a key can be
embraced by double quotes, no double quotes, or even be missing depending on the data type for a value.
Aside from string, number, and null data types, JSON data formatting also supports Boolean, array, and object data types.
This section presents progressively more advanced T-SQL programming examples for parsing JSON formatted text. There are sub-sections on
SQL Server instances with a compatibility level of 130 or higher (for SQL Server 2016+) make available the openjson table-valued function for parsing text in JSON format into columns and rows for display within a SQL query. The text must have a nvarchar data type. This Unicode specification of the input allows the openjson function to process international character sets.
Here is a simple T-SQL example illustrating some syntax guidelines for using the openjson function. The script begins with a use statement designating JsonDataProcessing as the default database name. You can use any other database that you prefer. Notice the local variable named @json has a nvarchar data type with a length of up to the maximum number of characters for nvarchar (about 2 gigabyte characters).
Notice that there is a select statement after the assignment of text representing JSON values to the @json local variable. The select statement displays the text in the @json local variable value as a table within SQL Server.The select statement uses the default schema for representing JSON values within the @json local variable. Here is the valid JSON:
use JsonDataProcessing
go
-- Json key name and type values
-- using type names for key values
-- array elements are string values
-- object element is for obj key with a string value
declare @json nvarchar(max) = N'{
"String_value": "Json key name and type values",
"Number_value": 12,
"Number_value": 12.3456,
"Boolean_value": true,
"Boolean_value": false,
"Null_value": null,
"Array_value": ["r","m","t","g","a"],
"Object_value": {"obj":"ect"}
}';
select * from openjson(@json);
Here is the results set from the trailing select statement in the preceding script. The @json value has a nvarchar data type populated with JSON formatted text. The results set has three columns for the key name, the type value, and a type number associated with each value type.

Here is another simple example for displaying JSON formatted data in SQL Server with the openjson function.
-- Json key name and type values
-- using selected other values than type names for key values
-- array elements are number values
-- object element is a number value
declare @json NVARCHAR(2048) = N'{
"String_value": "Json key name and type values",
"Integer": 12,
"F00": 12.3456,
"BooleanTrue_value": true,
"BooleanFalse_value": false,
"Null_value": null,
"Array_value": [1, 2, 3, 4, 5],
"Object_value": {"obj_2":1}
}';
select * from openjson(@json);
Here is the output from the select statement in the preceding script for your easy reference.

Instead of just having one JSON object within a nvarchar string, you can insert multiple Json objects within a string. Here is an example of some T-SQL code for implementing this capability. There are two distinct objects in the nvarchar string representing the JSON data.
The select statement at the end of the script outputs a separate row for each object. Objects are not explicitly assigned key names in the nvarchar string because they are top -level objects within the JSON document. Therefore, SQL Server arbitrarily assigns sequential integer values to a key field value when displaying the results set with the default schema.
-- two json objects in a nvarchar string
-- select statement uses the default schema
declare @json nvarchar(max);
set @json = N'[
{"id": 2, "age": 25},
{"id": 5, "dob": "2005-11-04T12:00:00"}
]';
select * from openjson(@json)
Here is the results
set from the preceding script.

The objects within
a JSON document can also have nested objects within them. Here is a T-SQL
example of how to represent this kind of relationship.
-- two json objects, each with a nested object, in a nvarchar string
-- with default schema for results set from select statement
declare @json nvarchar(max);
SET @json = N'[
{"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
{"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';
select * from openjson(@json)
The output from the preceding script appears next.

Using the default schema in a select statement is a quick and easy way to display JSON content from a local variable with the openjson function, but there are likely to be times when an application can benefit from a custom schema for displaying JSON content. With a custom schema, you can display native JSON content as if it were from a table in a SQL Server database.
There are just six JSON data types, and none of them is for a date. Therefore, if a select statement displays some JSON content that contains a datetime value with the default schema, the select statement displays the datetime value as a string in SQL Server. However, if you use a custom schema, you can transform the display so that it matches one of SQL Server’s datetime representations for the datetime value. In addition, there are many other benefits that custom schemas provide. This sub-section introduces you to some of these advantages, and another subsequent sub-section reinforces the benefits illustrated in this sub-section while also illustrating additional benefits.
You can specify a custom schema by using a with clause in a select statement. The with clause allows your code to associate a SQL Server data type representation to the type value for key-value pair within a JSON formatted string. This capability enables a select statement to display the content in a JSON document as if it were a value from a SQL Server table. In addition, key values for individual key-value pairs are separated into individual columns as if they were values from the columns of a SQL Server table.
Here is an
adaptation of the prior code sample that includes a with clause as part of the
select statement.
-- two json objects, each with a nested object, in a nvarchar string
-- with custom schema for results set from select statement
-- specified via with clause
declare @json NVARCHAR(MAX);
set @json = N'[
{"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
{"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';
select *
from openjson(@json)
with (
id INT '$.id',
firstName NVARCHAR(50) '$.info.name',
lastName NVARCHAR(50) '$.info.surname',
age int,
dateOfBirth datetime2 '$.dob'
);
Here is the output from the preceding T-SQL script.

This sub-section illustrates how to insert values from two different JSON documents into two different SQL Server tables. Then, it shows how to join the two SQL Server tables based on the values from key-value pairs from the original JSON documents.
Here is a script to copy a JSON document (@json) into a SQL Server table (dbo.sym_price_vol).
drop table if exists dbo.sym_price_vol
go
-- populate SQL Server table (dbo.sym_price_vol) with json string (@json)
declare @json nvarchar(max);
set @json = N'[{
"ticker_sym": "TSLA",
"date": "2021-04-19T12:00:00",
"open": 719.60,
"close": 714.63,
"vol": 39597000},
{
"ticker_sym": "TSLA",
"date": "2021-04-16T12:00:00",
"open": 728.65,
"close": 739.78,
"vol": 27924000},
{
"ticker_sym": "MSFT",
"date": "2021-04-19",
"open": 260.19,
"close": 258.74,
"vol": 23195800},
{
"ticker_sym": "MSFT",
"date": "2021-04-16",
"open": 259.47,
"close": 260.74,
"vol": 24856900}
]';
select *
into dbo.sym_price_vol
from openjson(@json)
with (
ticker_sym nvarchar(20),
date date,
[open] money,
[close] money,
vol bigint
)
Here is a second script to populate two rows in the dbo.sym_attribute table with values from another JSON formatted document. The purpose of the table is to store three attributes (shortName, sector, and industry) for each of two symbols (TSLA and MSFT). Because this script segment is designed to run optionally immediately after the preceding script it starts with a go keyword. The go keyword creates a fresh batch so that using a new declaration statement for a local variable named @json does not create a name conflict for the @json local variable.
drop table if exists dbo.sym_attributes
go
-- populate SQL Server table (dbo.sym_attributes) with json string (@json)
declare @json NVARCHAR(MAX);
set @json = N'[{
"ticker_sym": "TSLA",
"shortName": "Tesla, Inc.",
"sector": "Consumer Cyclical",
"industry": "Auto Manufacturers"},
{
"ticker_sym": "MSFT",
"shortName": "Microsoft Corporation",
"sector": "Technology",
"industry": "Software—Infrastructure"}
]';
select *
into dbo.sym_attributes
from openjson(@json)
with (
ticker_sym nvarchar(20),
shortName nvarchar(50),
sector nvarchar(50),
industry nvarchar(50)
)
Here are some
select statements for displaying the dbo.sym_price_vol and dbo.sym_attributes
tables separately as well as joined together.
-- display two populated tables from json values select * from dbo.sym_price_vol select * from dbo.sym_attributes -- join two tables populated with json data select sym_price_vol.* ,sym_attributes.shortName ,sym_attributes.sector ,sym_attributes.industry from dbo.sym_attributes inner join dbo.sym_price_vol on sym_attributes.ticker_sym = sym_price_vol.ticker_sym
Here are the results sets from the three preceding select statements.

This tip's download file contains a single T-SQL script with commented blocks that can generate all the results displayed in this tip. All T-SQL samples include one or more nvarchar declarations with assignments for some source JSON formatted data.
Years of Experience
Gratified Students
Training Batches
Training Hours
Please subscribe our technical blog to get recent updates.