T-SQL解析json字符串函数及其使用示例

参考博文:http://www.cnblogs.com/huangtailang/p/4277809.html

1、解析json字符串函数,返回表变量

ALTER FUNCTION [dbo].[parseJSON](@JSON NVARCHAR(MAX))RETURNS @hierarchy TABLE(element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */sequenceNo [int] NULL, /* the place in the sequence for the element */parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */NAME NVARCHAR(2000),/* the name of the object */StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/)ASBEGINDECLARE@FirstObject INT, --the index of the first open bracket found in the JSON string@OpenDelimiter INT,--the index of the next open bracket found in the JSON string@NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string@NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string@Type NVARCHAR(10),--whether it denotes an object or an array@NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'@Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression@Start INT, --index of the start of the token that you are parsing@end INT,--index of the end of the token that you are parsing@param INT,--the parameter at the end of the next Object/Array token@EndOfName INT,--the index of the start of the parameter at end of Object/Array token@token NVARCHAR(200),--either a string or object@value NVARCHAR(MAX), -- the value as a string@SequenceNo int, -- the sequence number within a list@name NVARCHAR(200), --the name as a string@parent_ID INT,--the next parent ID to allocate@lenJSON INT,--the current length of the JSON String@characters NCHAR(36),--used to convert hex to decimal@result BIGINT,--the value of the hex symbol being parsed@index SMALLINT,--used for parsing the hex value@Escape INT --the index of the next escape characterDECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */(String_ID INT IDENTITY(1, 1),StringValue NVARCHAR(MAX))SELECT--initialise the characters to convert hex to ascii@characters='0123456789abcdefghijklmnopqrstuvwxyz',@SequenceNo=0, --set the sequence no. to something sensible./* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */@parent_ID=0;WHILE 1=1 --forever until there is nothing more to doBEGINSELECT@start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited stringIF @start=0 BREAK --no more so drop through the WHILE loopIF SUBSTRING(@json, @start+1, 1)='"'BEGIN --Delimited NameSET @start=@Start+1;SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);ENDIF @end=0 --no end delimiter to last stringBREAK --no moreSELECT @token=SUBSTRING(@json, @start+1, @end-1)--now put in the escaped control charactersSELECT @token=REPLACE(@token, FROMString, TOString)FROM(SELECT'\"' AS FromString, '"' AS ToStringUNION ALL SELECT '\\', '\'UNION ALL SELECT '\/', '/'UNION ALL SELECT '\b', CHAR(08)UNION ALL SELECT '\f', CHAR(12)UNION ALL SELECT '\n', CHAR(10)UNION ALL SELECT '\r', CHAR(13)UNION ALL SELECT '\t', CHAR(09)) substitutionsSELECT @result=0, @escape=1--Begin to take out any hex escape codesWHILE @escape>0BEGINSELECT @index=0,--find the next hex escape sequence@escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)IF @escape>0 --if there is oneBEGINWHILE @index<4 --there are always four digits to a \x sequence  BEGINSELECT --determine its value@result=@result+POWER(16, @index)*(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),@characters)-1), @index=@index+1 ;END-- and replace the hex sequence by its unicode valueSELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))ENDEND--now store the string awayINSERT INTO @Strings (StringValue) SELECT @token-- and replace the string with a tokenSELECT @JSON=STUFF(@json, @start, @end+1,'@string'+CONVERT(NVARCHAR(5), @@identity))END-- all strings are now removed. Now we find the first leaf. WHILE 1=1  --forever until there is nothing more to doBEGINSELECT @parent_ID=@parent_ID+1--find the first object or list by looking for the open bracketSELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or arrayIF @FirstObject = 0 BREAKIF (SUBSTRING(@json, @FirstObject, 1)='{')SELECT @NextCloseDelimiterChar='}', @type='object'ELSESELECT @NextCloseDelimiterChar=']', @type='array'SELECT @OpenDelimiter=@firstObjectWHILE 1=1 --find the innermost object or list...BEGINSELECT@lenJSON=LEN(@JSON+'|')-1--find the matching close-delimiter proceeding after the open-delimiterSELECT@NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,@OpenDelimiter+1)--is there an intervening open-delimiter of either typeSELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--objectIF @NextOpenDelimiter=0BREAKSELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiterIF @NextCloseDelimiter<@NextOpenDelimiterBREAKIF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'SELECT @NextCloseDelimiterChar='}', @type='object'ELSESELECT @NextCloseDelimiterChar=']', @type='array'SELECT @OpenDelimiter=@NextOpenDelimiterEND---and parse out the list or name/value pairsSELECT@contents=SUBSTRING(@json, @OpenDelimiter+1,@NextCloseDelimiter-@OpenDelimiter-1)SELECT@JSON=STUFF(@json, @OpenDelimiter,@NextCloseDelimiter-@OpenDelimiter+1,'@'+@type+CONVERT(NVARCHAR(5), @parent_ID))WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0BEGINIF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or nullBEGINSELECT@SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAASELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),@endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),@param=RIGHT(@token, LEN(@token)-@endofname+1)SELECT@token=LEFT(@token, @endofname-1),@Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)SELECT  @name=stringvalue FROM @stringsWHERE string_id=@param --fetch the nameENDELSESELECT @Name=null,@SequenceNo=@SequenceNo+1SELECT@end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or nullIF @end=0SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin)+1SELECT@start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--select @start,@end, LEN(@contents+'|'), @contents SELECT@Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),@Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)IF SUBSTRING(@value, 1, 7)='@object'INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),SUBSTRING(@value, 8, 5), 'object'ELSEIF SUBSTRING(@value, 1, 6)='@array'INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),SUBSTRING(@value, 7, 5), 'array'ELSEIF SUBSTRING(@value, 1, 7)='@string'INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, ValueType)SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'FROM @stringsWHERE string_id=SUBSTRING(@value, 8, 5)ELSEIF @value IN ('true', 'false')INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, ValueType)SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'ELSEIF @value='null'INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, ValueType)SELECT @name, @SequenceNo, @parent_ID, @value, 'null'ELSEIF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0INSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, ValueType)SELECT @name, @SequenceNo, @parent_ID, @value, 'real'ELSEINSERT INTO @hierarchy(NAME, SequenceNo, parent_ID, StringValue, ValueType)SELECT @name, @SequenceNo, @parent_ID, @value, 'int'if @Contents=' ' Select @SequenceNo=0ENDENDINSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)SELECT '-',1, NULL, '', @parent_id-1, @type--
RETURNEND

2、存储过程调用示例

ALTER PROCEDURE [dbo].[P_CallparseJSONTest]
(@sSenJsonInfo nvarchar(MAX)    --json字符串,@nBackInfo INT OUTPUT         --存储过程标识, 1-成功;-1-失败
)
AS
BEGINDECLARE @parent_ID INTDECLARE @hierarchy TABLE(element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */sequenceNo [int] NULL, /* the place in the sequence for the element */parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */NAME NVARCHAR(2000),/* the name of the object */StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/)BEGIN TRANBEGIN tryIF @sSenJsonInfo!=''BEGININSERT INTO @hierarchy(sequenceNo,parent_ID,Object_ID,NAME,StringValue,ValueType) SELECT sequenceNo,parent_ID,Object_ID,NAME,StringValue,ValueType FROM dbo.parseJSON(@sSenJsonInfo)IF @@error<>0BEGINROLLBACK TRANRETURN 0ENDENDELSEBEGINSET @nBackInfo = 0    RETURNENDSET @nBackInfo = 1    --成功END tryBEGIN catchSET @nBackInfo = -1        --失败END catchIF @@error<>0BEGINROLLBACK TRANRETURN 0ENDELSEBEGINCOMMIT TRANRETURN 1END
END

......

转载于:https://www.cnblogs.com/yuzhihui/p/5465832.html

T-SQL解析json字符串函数相关推荐

  1. sql解析json格式字段、sql关联json格式字段,mysql解析json、sql解析json字符串

    sql解析json格式字段.sql关联json格式字段,mysql解析json.sql解析json字符串 sql解析字符串 sql关联json中的某个字段 sql解析字符串 表名user_login ...

  2. Oracle怎么获取json类型字符串值,sql解析json格式字段 如何获取json中某个字段的值?...

    java将json数据解析为sql语句?小编给你倒一杯热水.可你惦记着其他饮料,所以你将它放置一旁.等你想起那杯水时,可惜它已经变得冰冷刺骨. 图片中是json数据,每个数据的开头都有表名称,操作类型 ...

  3. MySQL解析json字符串的相关问题

    很多时候,我们需要在sql里面直接解析json字符串.这里针对mysql5.7版本的分水岭进行区分. 查看MySQL版本: SELECT VERSION(); 对于mysql5.7以上版本 使用mys ...

  4. mysql解析json字符串_Mysql解析json字符串/数组

    1 Mysql解析json字符串 解决方法:JSON_EXTRACT(原字段,'$.json字段名') 执行SQL: SELECT JSON_EXTRACT( t.result,'$.row'), J ...

  5. sql中截取字符串函数_SQL Server 2017中的顶级SQL字符串函数

    sql中截取字符串函数 SQL Server 2017 has been in the talk for its many features that simplify a developer's l ...

  6. Hive sql解析json格式

    ** hive sql解析json格式 /*方法一: select regexp_extract(input_data,'app_id\\":\\"(.*?)\\"',1 ...

  7. javascript解析json字符串,各种格式分析

    javascript解析json字符串,各种格式分析 JS,JSON,EVAL函数说明 JSON.parse(字符串) 方法用于将一个 JSON 字符串转换为对象 JSON.stringify(对象或 ...

  8. js解析json字符串、对象与json之间的转换

    前言 在数据传输流程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键. js解析json字符串 // JSON字符串 'v ...

  9. jquery parseJSON()方法解析json字符串

    在web项目开发中,前端经常需要接收后端传送来的json数据,解析json字符串,再对页面进行渲染.使用jquery解析json字符串通常需要将json字符串转化为javascript的json对象( ...

最新文章

  1. 第五章ThinkingInJava
  2. php 递归太多报错,PHP、递归 - 角落里的星辰的个人空间 - OSCHINA - 中文开源技术交流社区...
  3. config对象的使用及常用方法
  4. 信号 应用场景 内置信号 内置信号操作 自定义信号
  5. 哪种HTML列表会自动编号,HTML列表的种类
  6. 机箱硬盘指示灯不亮_安钛克DF600 FLUX机箱:FLUX平台第一款机箱,为全民电竞热“降温”...
  7. 华农专业课计算机基础,华南农业大学期末考试大学计算机基础试卷.doc
  8. java View转换类型_java强制类型转换.
  9. 关于crossvalind函数(转)
  10. pandas根据现有列新添加一列
  11. 章节3.4----队列的实现与应用
  12. 解决办法:ImportError: 'module' object has no attribute 'check_specifier'
  13. GUID和UUID、CLSID、IID 区别及联系
  14. 第三届易观算法大赛 -- OLAP Session分析(5万奖金)
  15. 23中设计模式之策略模式
  16. 做一名「技术掮客」去变现自己的技术
  17. python统计元音字母个数_Quzh[python]统计元音字母——输入一个字符串,统计处其中元音字母的数量。...
  18. 小米、Vivo、Oppo后台弹出界面和锁屏权限检测
  19. 用平面图片制作3D模型【3DsMax】
  20. RK3399 Android7.1使用网络连接ADB

热门文章

  1. Java:JSON解析工具-json-lib
  2. Clamav杀毒安装配置手册
  3. android连接ios热点超时,Android19连接iOS13个人热点失败
  4. 利用Python批量识别电子账单数据
  5. 霍夫变换论文、代码汇总
  6. 怎么样才能让自己自律起来_怎样让懒惰的人自律起来?
  7. c语言80c51控制系统设计,基于AT89C51的国旗升降控制系统设计
  8. Ubuntu安装配置串口通讯工具minicomcutecom
  9. 使用Python画出ROC曲线后,如何在ROC曲线代码中增加95%CI?
  10. 「衣米魔兽世界怀旧服」大数据分析反外挂系统查封145个穿门账号