JSON
JSON is a text format that is completely language-independent. Meaning it does not dependent on any specific programming language. It is a very lightweight data-interchange format. Moreover, very easy for humans to read and write.
OPENJSON
OpenJSON is a SQL function. That converts JSON text and returns a key and value in a row and column format. Meaning it helps to make JSON queryable.
Note
Microsoft suggests storing JSON text using the nvarchar(max) data type. This data type supports up to 2GB of storage per value. The OPENJSON function available under compatibility level 130.

OPENJSON has 2 arguments and one clause option. Like:
JSONExpression Argument
JSON Expression means JSON text. It is a required argument for this function. So they must be defined by the JSON Expression.

DECLARE @json NVARCHAR(MAX)
SET @json = N'
{
"id":1,
"team": "Bangladesh",
"player": {
"name": "Mashrafe Murtuza",
"size": {
"width": "74 kg",
"hight": "6.1 feet"
}
},
"opposite_team": null,
"captain": ["Mashrafe Murtuza (C)", "Tamim Iqbal (VC)"],
"good_position": true,
"icc_associate_member": 1977
}'
select * from OPENJSON(@json) order by type
Note
Remember that type is an auto-generated column according to JSON data type.

Path Argument
Meaning retrieving a specific object of JSON Expression/text. It is an optional argument. The path always begins with a dollar ($) sign. There are two modes for using Path. Like:
Lax Mode
It is the default mode. So, no need to explicitly define the Lax keyword. If the path does not exist, it will return a NULL or empty row and not raise any error in executing time if the path does not exist.

DECLARE @json NVARCHAR(MAX)
SET @json = N'
{
"id":1,
"team": "Bangladesh",
"player": {
"name": "Mashrafe Murtuza",
"size": {
"width": "74 kg",
"hight": "6.1 feet"
}
},
"opposite_team": null,
"captain": ["Mashrafe Murtuza (C)", "Tamim Iqbal (VC)"],
"good_position": true,
"icc_associate_member": 1977
}'
select * from OPENJSON(@json, '$.player.size') order by type
When not exists the explicit path in Lax mode.

DECLARE @json NVARCHAR(MAX)
SET @json = N'
{
"id":1,
"team": "Bangladesh",
"player": {
"name": "Mashrafe Murtuza",
"size": {
"width": "74 kg",
"hight": "6.1 feet"
}
},
"opposite_team": null,
"captain": ["Mashrafe Murtuza (C)", "Tamim Iqbal (VC)"],
"good_position": true,
"icc_associate_member": 1977
}'
select * from OPENJSON(@json, '$.player.type') order by type
Strict Mode
It will raise an error in executing time if an explicit path does not exist. We need to define the explicitly strict keyword with $ sign.







Join the conversation! Your thoughts help the community grow.