Parsing json in SQL Server

1. Parse json

Applies to: SQL Server 2016 (13.x) and later Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics SQL endpoints in Microsoft Fabric Warehouses in Microsoft Fabric

(1)Use OPENJSON() function
declare @json as varchar(8000)
set @json='[
{"id":1178,"myObject.Plies":3,"myObject.Createtime":"2020-07-21T14:33:18.480"},
{"id":1179,"myObject.Plies":3,"myObject.Createtime":"2020-07-21T14:36:27.457"}]'
select * from openjson(@json);

Insert image description here

(2) Customize the output column through WITH selection
declare @json2 as varchar(8000)
set @json2='{"myRoot":[
{"id":1178,"myObject":{"Plies":3,"Createtime":"2020-07-21T14:33:18.480"}},
{"id":1179,"myObject":{"Plies":3,"Createtime":"2020-07-21T14:36:27.457"}}
]}'
 
select * from openjson(@json2,'$.myRoot')
with(
id varchar(10) ,
Plies  int '$.myObject.Plies',
Createtime datetime '$.myObject.Createtime'
);

Insert image description here

2.Json function

(1) ISJSON: Test whether the string contains valid JSON.

print iif(isjson(@param) > 0, 'OK', 'NO');

2. JSON_VALUE: Extract scalar value from JSON string.

print json_value(@param, '$.info.address.town');
print json_value(@param, '$.info.tags[1]');

3. JSON_QUERY: Extract objects or arrays from JSON strings. Returns a JSON fragment of type nvarchar(max)

print json_query(@param, '$.info');
{    
       "type":1,  
       "address":{    
         "town":"Bristol",  
          "county":"Avon",  
          "country":"England"  
        },  
        "tags":["Sport", "Water polo"]  
}

4. JSON_MODIFY: Update the value of the attribute in the JSON string and return the updated JSON string.

print json_modify(@param, '$.info.address.town', 'London');

return:

{  
     "info":{    
       "type":1,  
       "address":{    
         "town":"London",  
         "county":"Avon",  
          "country":"England" 
        },  
        "tags":["Sport", "Water polo"]  
     },  
     "type":"Basic" 
  }

Example demo code

declare @param nvarchar(max);
set @param=N'{  
     "info":{    
       "type":1,  
       "address":{    
         "town":"Bristol",  
         "county":"Avon",  
         "country":"England"  
       },  
       "tags":["Sport", "Water polo"]  
    },  
    "type":"Basic"  
 }';

print iif(isjson(@param)>0, 'OK', 'NO');
print json_query(@param);
print json_value(@param, '$.info.address.town');
print json_value(@param, '$.info.tags[1]');
print json_query(@param, '$.info');
print json_query('["2020-1-8","2020-1-9"]');
print json_modify(@param, '$.info.address.town', 'London');

Official documentation: https://learn.microsoft.com/zh-cn/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16

Guess you like

Origin blog.csdn.net/weixin_49543015/article/details/133344969