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

Working With JSON in SQL

Last Updated : 19 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 for front-end applications like Android, iOS, React, Angular, etc.

In this article, we will learn how to store, retrieve, and manipulate JSON data in SQL Server using various SQL functions. We will learn how JSON fits into SQL, demonstrate how to store JSON data in SQL tables and cover the most common JSON functions like ISJSON(), JSON_VALUE(), JSON_MODIFY(), and more.

What is JSON in SQL Server?

JSON is a lightweight data-interchange format that is easy for humans to read and write. SQL Server introduced native support for JSON handling starting from SQL Server 2016. This allows you to store JSON data in NVARCHAR columns and use SQL functions to parse, query, and modify JSON data.

Storing JSON in SQL Server

In SQL Server, you can store JSON data as a string in an NVARCHAR column. SQL Server treats JSON data as a string, allowing you to parse it when necessary.

Creating Tables with Data

Now let us create a table named “Authors” and let us insert some data into 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"}]
  }
}

Example 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

Example 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

Example 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

LIST OF SCHOOLS BY MEANS OF JSON_QUERY

Example 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;

Example 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.

Authors table output

SELECT * FROM Authors FOR JSON AUTO;

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

Example 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'

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

Select * FROM OPENJSON (@JSON)

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')

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) )

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)
)

Example 7: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;

Conclusion

Handling JSON in SQL Server enables seamless interaction with modern web applications and NoSQL databases. The ability to store, query, and manipulate JSON data directly in SQL Server enhances the flexibility and efficiency of your data management system. SQL Server’s native JSON functions—such as ISJSON(), JSON_VALUE(), JSON_QUERY(), and JSON_MODIFY()—make it easier to integrate and work with JSON data without needing a separate NoSQL system.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg