close
The Wayback Machine - https://web.archive.org/web/20240702234627/https://www.geeksforgeeks.org/working-with-json-in-sql/
Open In App

Working With JSON in SQL

Last Updated : 23 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

JSON stands for Javascript Object Notation. It is mainly used in storing and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB, etc., use JSON format data. Whenever your data from one server has to be transferred to a web page, JSON format is the preferred format as front-end applications like Android, iOS, React or Angular, etc., can parse the JSON contents and display them according to convenience. Even in SQL, we can send JSON data and can store them easily in rows. Let us see one by one.

Let us use Azure Data Studio for SQL Server. Let us also create the database and have a table in place. Then can proceed for JSON. Azure Data Studio works well for Windows 10, Mac, and Linux environments. It can be installed from here.

Database creation :

Command to create the database.  Here GEEKSFORGEEKS is the db name.

CREATE DATABASE GEEKSFORGEEKS;

To make the database active use the below command:

USE GEEKSFORGEEKS;

BERJAYA

Creating Tables with Data:

Now let us create a table named “Authors” and let us insert some data to it as shown below:

CREATE TABLE Authors (
    ID INT IDENTITY NOT NULL PRIMARY KEY,
    AuthorName NVARCHAR(MAX),
    Age INT,
    Skillsets NVARCHAR(MAX),
    NumberOfPosts INT
);
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES ('Geek',25,'Java,Python,.Net',5);
GO

INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES ('Geek2',22,'Android,Python,.Net',15);
GO
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES ('Geek3',23,'IOS,GO,R',10);
GO
INSERT INTO Authors (AuthorName,Age,Skillsets,NumberOfPosts) VALUES ('Geek4',24,'Java,Python,GO',5);
GO

JSON is a beautiful option for bridging NoSQL and relational worlds. Hence, in case if you have the data got exported from MongoDB and need to import them in SQL Server, we can follow below approaches

JSON documents can be stored as-is in NVARCHAR columns either in LOB storage format or Relational storage format. Raw JSON documents have to be parsed, and they may contain Non-English text.  By using nvarchar(max) data type, we can store JSON documents with a max capacity of 2 GB in size. If the JSON data is not huge, we can go for  NVARCHAR(4000), or else we can go for NVARCHAR(max) for performance reasons.

Cross feature compatibility:

The main reason for keeping the JSON document in NVARCHAR  format is for Cross feature compatibility. NVARCHAR  works with X feature i.e. all the SQL server components such as Hekaton(OLTP), temporal, or column store tables, etc. As JSON behavior is also in that way, it is represented as NVARCHAR datatype.

Migration:

Before SQL Server 2016, JSON was stored in the database as text. Hence, there was a need to change the database schema and migration occurred as JSON type in NVarchar format

Client-side support:

JSON is just treated as an Object in JavaScript and hence called as Javascript Object Notation. There is no specific  standardized JSON object type on client-side available similar to XmlDom object.

Let us see the important functionalities available in SQL Server which can be used with JSON data.

Example JSON Data :

{
"Information": 
  {"SchoolDetails": 
     [{"Name": "VidhyaMandhir"}, {"Name": "Chettinad"}, {"Name":"PSSenior"}]
  }
}

1. ISJSON (JSON string):

This function is used to check whether the given input json string is in JSON format or not. If it is in JSON format, it returns 1 as output or else 0. i.e. it returns either 1 or 0 in INT format.

SELECT ISJSON(@JSONData) AS VALIDJSON

BERJAYA

2. JSON_VALUE (JSON string, path):

 The output will be a scalar value from the given JSON string. Parsing of JSON string is done and there are some specific formats are there for providing the path. For example

  • ‘$’ – reference entire JSON object
  • ‘$.Example1’ – reference Example1in JSON object
  • ‘$[4]’ – reference 4th element in JSON array
  • ‘$.Example1.Example2[2].Example3’ – reference nested property in JSON object

Example :

SELECT JSON_VALUE(@JSONData,'$.Information.SchoolDetails[0].Name') as SchoolName

BERJAYA

3. JSON_QUERY(JSON string, path)

Used to extract an array of data or objects from the JSON string.

SELECT JSON_QUERY(@JSONData,'$.Information.SchoolDetails')
AS LISTOFSCHOOLS
BERJAYA

LIST OF SCHOOLS BY MEANS OF JSON_QUERY

4. JSON_MODIFY:

There is an option called “JSON_MODIFY” in  (Transact-SQL) function is available to update the value of a property in a JSON string and return the updated JSON string. Whenever there is a requirement to change JSON text, we can do that

SET @JSONData= JSON_MODIFY(@JSONData, '$.Information.SchoolDetails[2].Name', 'Adhyapana');
SELECT modifiedJson = @JSONData;

BERJAYA

5. FOR JSON : 

This function is used for Exporting SQL Server data as JSON format. This is a useful function to export SQL  data into JSON format.  There are two options available with FOR JSON

  • AUTO: As it is nested JSON sub-array is created based on the table hierarchy.
  • PATH:  By using this we can define the structure of JSON in a customized way.
BERJAYA

Authors table output

SELECT * FROM Authors FOR JSON AUTO;

BERJAYA

SELECT * FROM Authors FOR JSON AUTO, ROOT ('AuthorInfo')

BERJAYA

6. OPENJSON  :

This function is used for importing JSON as String data. We can import JSON as a text file by using OPENROWSET function and in that the BULK option should be enabled. It returns a single string field with BulkColumn as its column name.

Example :

DECLARE @JSON VARCHAR(MAX)
--Syntax to get json data using OPENROWSET  
SELECT @JSON = BulkColumn FROM OPENROWSET  
(BULK '<pathname\jsonfilename with .json extension>', SINGLE_CLOB)  AS j
--To check  json valid or not, we are using this ISJSON
SELECT ISJSON(@JSON)
--If ISJSON is true, then display the json data
If (ISJSON(@JSON)=1)
SELECT @JSON AS 'JSON Text'

BERJAYA

Note: Even large data also can be placed. As a sample, we showed only a single row.

SINGLE_BLOB, which reads a file as varbinary(max). SINGLE_NCLOB, which reads a file as nvarchar(max)  — If the contents are in Non-English text like Japanese or Chinese etc., data, we need to go in this pattern.  We used SINGLE_CLOB, which reads a file as varchar(max).

It will generate a relational table with its contents from the JSON string. Each row is created which can be got by iterating through JSON object elements, OPENJSON  can be used to parse the JSON as a text. Let us have a JSON placed in an external file and its contents are

BERJAYA

Select * FROM OPENJSON (@JSON)

BERJAYA

SELECT @JSON = BulkColumn
FROM OPENROWSET 
(BULK '<location of json file>', SINGLE_CLOB) 
AS j
--If the retrieved JSON is a valid one
If (ISJSON(@JSON)=1)
Select * FROM OPENJSON (@JSON)

We can see that for “Strings” key like “authorname” and “skills” got type as 1 and “int” key like “id” and “age” got type as 2. Similarly, for boolean, the type is 3. For arrays, it is 4 and for object, it is 5. OPENJSON  parses only the root level of the JSON.

In case if the JSON is nested, we need to use Path variables

Select * FROM OPENJSON (@JSON,  '$.skills')

BERJAYA

We can even make the skillsets as columns of data as

SELECT * FROM OPENJSON (@JSON, '$.skills')  
WITH ( skill1 VARCHAR(25), skill2 VARCHAR(25), skill3 VARCHAR(25) )

BERJAYA

Saving the rowset into Table: Here the number of columns should match the count that is present inside with:

SELECT <col1>,<col2>,.... INTO <tablename>  FROM OPENJSON (@JSON, '$.skills')  
WITH (skill1 VARCHAR(25),
skill2 VARCHAR(25),
skill3 VARCHAR(25)
)

BERJAYA

Changing JSON values :

There is an option called “JSON_MODIFY” in  (Transact-SQL) function is available to update the value of a property in a JSON string and return the updated JSON string. Whenever there is a requirement to change JSON text, we can do that

DECLARE @json NVARCHAR(MAX);
SET @json = '{"Information": {"SchoolDetails": [{"Name": "VidhyaMandhir"}, {"Name": "Chettinad"}, {"Name":"PSSenior"}]}}';
SET @json = JSON_MODIFY(@json, '$.Information.SchoolDetails[2].Name', 'Adhyapana');
SELECT modifiedJson = @json;

BERJAYA

Conclusion :

JSON data is very much necessary nowadays and it is much required for storing and transportation of data across many servers and all software are using this for many useful purposes. All REST API calls provide JSON as output medium and in SQL Server , we have see how to use them.



Previous Article
Next Article

Similar Reads

Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
How to Import JSON Data into SQL Server?
JSON (Javascript Object Notation) is a lightweight text-based data format that is used to interchange data between different systems. It is based on a subset of the Javascript programming language. It also enables us to integrate NoSQL and related concepts into the same database. You might need to import JSON data into SQL Server if you want to use
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
Difference between SQL and T-SQL
1. Structured Query language (SQL): A structured Query language is a computer language for a relational database system. Relational database system like MySQL oracle Sybase Informix uses SQL as standard database language for storing retrieving manipulating data and store in a relational database. Here are some SQL commands that are used for communi
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
Article Tags :