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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值