This is one of the new features of SQL Server 2016. Before this article, I would like you to go through one of the previous articles on the Split_String function in SQL Server 2016.
I hope you love this new feature of SQL Server. Let’s move on to the ISJSON() function.
What is JSON?
JSON (JavaScript Object Notation) is a text based format, used for data exchange. It is lightweight compared to XML and thus is preferred as a best choice to transfer the data across the devices. It is open and readable. We can parse JSON by JavaScript implementations. Because of a few of these features, the developers prefer JSON over XML these days.
JSON Syntax
Here, I will show what JSON looks like:
- {"students":[
- {"Name":"James", "Age":27},
- {"Name":"John Doe", "Age":28},
- {"Name":"John Smith", "Age":29}
- ]}
SQL Server 2016 has introduced a new function that can validate whether the input passed is JSON or not. If JSON is correct, the value is 1 and that would be TRUE, and if it returns 0 then it means there is something wrong with the JSON format and it is False.
Let us see how this function works. Open SQL Server 2016 and write the following script in the Query Editor.
- DECLARE @JSONINPUT NVARCHAR(4000)
- SET @JSONINPUT = N'{"students":[
- {"Name":"James", "Age":27},
- {"Name":"John Doe", "Age":28},
- {"Name":"John Smith", "Age":29}
- ]}'
- IF (ISJSON(@JSONINPUT) = 1)
- BEGIN
- PRINT 'This is JSON!!'
- END
- ELSE
- BEGIN
- PRINT 'NOT a JSON!!'
- END
- GO
Let us execute the script and see if we get the correct output or not. We should be able to see “This is JSON” as the output.
Thus, we get the expected output. Let us make some modifications to JSON that we have passed as an input to the function. I’ll remove one of the brackets from JSON and check for the output. Let us see what happens:
- DECLARE @JSONINPUT NVARCHAR(4000)
- SET @JSONINPUT = N '{"students":[
- {
- "Name": "James",
- "Age": 27
- },
- {
- "Name": "John Doe",
- "Age": 28
- }, "Name": "John Smith", "Age": 29
- }]
- }
- '
- IF(ISJSON(@JSONINPUT) = 1)
- BEGIN
- PRINT 'This is JSON!!'
- END
- ELSE
- BEGIN
- PRINT 'NOT a JSON!!'
- END
- GO
Execute the preceding script.
Since JSON is not valid, the function returns an invalid JSON message. This validates the functionality of ISJSON() function in SQL Server 2016.
Let us pass null into the function and check what will be the output:
We get null as the output. For null, this function will return null as the output.
Summary
In this post, we saw a very new feature i.e., ISJSON() function and how it can be used. This is very helpful for the developers as the same functionality can be used in SQL itself.