SQL Server中解析json

1.解析json

适用于:SQL Server 2016 (13.x) 及更高版本Azure SQL 数据库Azure SQL 托管实例Azure Synapse AnalyticsMicrosoft Fabric 中的 SQL 终结点Microsoft Fabric 中的仓库

(1)使用OPENJSON()函数
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);

在这里插入图片描述

(2)通过WITH选型,自定义输出列
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'
);

在这里插入图片描述

2.Json函数

(1) ISJSON:测试字符串是否包含有效 JSON。

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

2、JSON_VALUE :从 JSON 字符串中提取标量值。

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

3、JSON_QUERY :从 JSON 字符串中提取对象或数组。返回类型为 nvarchar(max) 的 JSON 片段

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

4、JSON_MODIFY :更新 JSON 字符串中属性的值,并返回已更新的 JSON 字符串。

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

返回:

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

实例演示代码

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

官方文档:https://learn.microsoft.com/zh-cn/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16

猜你喜欢

转载自blog.csdn.net/weixin_49543015/article/details/133344969