sql server json 字符串处理

JSON format.

JSON is designed to be as lightweight as possible and so it has only two structures. The first, delimited by curly brackets, is a collection of name/value pairs, separated by commas. The name is followed by a colon. This structure is generally implemented in the application-level as an object, record, struct, dictionary, hash table, keyed list, or associative array. The other structure is an ordered list of values, separated by commas. This is usually manifested as an array, vector, list, or sequence.

"Using recursion in TSQL is 
like Sumo Wrestlers doing Ballet. 
It is possible but not pretty."

The first snag for TSQL is that the curly or square brackets are not 'escaped' within a string, so that there is no way of shredding a JSON 'document' simply. It is difficult to  differentiate a bracket used as the delimiter of an array or structure, and one that is within a string. Also, interpreting a string into a SQL String isn't entirely straightforward since hex codes can be embedded anywhere to represent complex Unicode characters, and all the old C-style escaped characters are used. The second complication is that, unlike YAML, the datatypes of values can't be explicitly declared. You have to sniff them out from applying the rules from the JSON Specification.

Obviously, structures can be embedded in structures, so recursion is a natural way of making life easy. Using recursion in TSQL is like Sumo Wrestlers doing Ballet. It is possible but not pretty.

The implementation

Although the code for the JSON Parser/Shredder will run in SQL Server 2005, and even in SQL Server 2000 (with some modifications required), I couldn't resist using a TVP (Table Valued Parameter) to pass a hierarchical table to the function, ToJSON, that produces a JSON 'document'. Writing a SQL Server 2005 version should not be too hard.

First the function replaces all strings with tokens of the form @Stringxx, where xx is the foreign key of the table variable where the strings are held. This takes them, and their potentially difficult embedded brackets, out of the way. Names are  always strings in JSON as well as  string values.

Then, the routine iteratively finds the next structure that has no structure contained within it, (and is, by definition the leaf structure), and parses it, replacing it with an object token of the form '@Objectxxx', or '@arrayxxx', where xxxis the object id assigned to it. The values, or name/value pairs are retrieved from the string table and stored in the hierarchy table. Gradually, the JSON document is eaten until there is just a single root object left.

The JSON outputter is a great deal simpler, since one can be surer of the input, but essentially it does the reverse process, working from the root to the leaves. The only complication is working out the indent of the formatted output string.

In the implementation, you'll see a fairly heavy use of PATINDEX. This uses a poor man's RegEx, a starving man's RegEx. However, it is all we have, and can be pressed into service by chopping the string it is searching (if only it had an optional third parameter like CHARINDEX that specified the index of the start position of the search!). The STUFF function is also a godsend for this sort of string-manipulation work.

 

  1 CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))
  2 
  3 RETURNS @hierarchy TABLE
  4 
  5   (
  6 
  7    element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
  8 
  9    sequenceNo [int] NULL, /* the place in the sequence for the element */
 10 
 11    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 */
 12 
 13    Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
 14 
 15    NAME NVARCHAR(2000),/* the name of the object */
 16 
 17    StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
 18 
 19    ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
 20 
 21   )
 22 
 23 AS
 24 
 25 BEGIN
 26 
 27   DECLARE
 28 
 29     @FirstObject INT, --the index of the first open bracket found in the JSON string
 30 
 31     @OpenDelimiter INT,--the index of the next open bracket found in the JSON string
 32 
 33     @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
 34 
 35     @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
 36 
 37     @Type NVARCHAR(10),--whether it denotes an object or an array
 38 
 39     @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
 40 
 41     @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
 42 
 43     @Start INT, --index of the start of the token that you are parsing
 44 
 45     @end INT,--index of the end of the token that you are parsing
 46 
 47     @param INT,--the parameter at the end of the next Object/Array token
 48 
 49     @EndOfName INT,--the index of the start of the parameter at end of Object/Array token
 50 
 51     @token NVARCHAR(200),--either a string or object
 52 
 53     @value NVARCHAR(MAX), -- the value as a string
 54 
 55     @SequenceNo int, -- the sequence number within a list
 56 
 57     @name NVARCHAR(200), --the name as a string
 58 
 59     @parent_ID INT,--the next parent ID to allocate
 60 
 61     @lenJSON INT,--the current length of the JSON String
 62 
 63     @characters NCHAR(36),--used to convert hex to decimal
 64 
 65     @result BIGINT,--the value of the hex symbol being parsed
 66 
 67     @index SMALLINT,--used for parsing the hex value
 68 
 69     @Escape INT --the index of the next escape character
 70 
 71    
 72 
 73  
 74 
 75   DECLARE @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 */
 76 
 77     (
 78 
 79      String_ID INT IDENTITY(1, 1),
 80 
 81      StringValue NVARCHAR(MAX)
 82 
 83     )
 84 
 85   SELECT--initialise the characters to convert hex to ascii
 86 
 87     @characters='0123456789abcdefghijklmnopqrstuvwxyz',
 88 
 89     @SequenceNo=0, --set the sequence no. to something sensible.
 90 
 91   /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
 92 
 93     @parent_ID=0;
 94 
 95   WHILE 1=1 --forever until there is nothing more to do
 96 
 97     BEGIN
 98 
 99       SELECT
100 
101         @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string
102 
103       IF @start=0 BREAK --no more so drop through the WHILE loop
104 
105       IF SUBSTRING(@json, @start+1, 1)='"'
106 
107         BEGIN --Delimited Name
108 
109           SET @start=@Start+1;
110 
111           SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collateSQL_Latin1_General_CP850_Bin);
112 
113         END
114 
115       IF @end=0 --no end delimiter to last string
116 
117         BREAK --no more
118 
119       SELECT @token=SUBSTRING(@json, @start+1, @end-1)
120 
121       --now put in the escaped control characters
122 
123       SELECT @token=REPLACE(@token, FROMString, TOString)
124 
125       FROM
126 
127         (SELECT
128 
129           '\"' AS FromString, '"' AS ToString
130 
131          UNION ALL SELECT '\\', '\'
132 
133          UNION ALL SELECT '\/', '/'
134 
135          UNION ALL SELECT '\b', CHAR(08)
136 
137          UNION ALL SELECT '\f', CHAR(12)
138 
139          UNION ALL SELECT '\n', CHAR(10)
140 
141          UNION ALL SELECT '\r', CHAR(13)
142 
143          UNION ALL SELECT '\t', CHAR(09)
144 
145         ) substitutions
146 
147       SELECT @result=0, @escape=1
148 
149   --Begin to take out any hex escape codes
150 
151       WHILE @escape>0
152 
153         BEGIN
154 
155           SELECT @index=0,
156 
157           --find the next hex escape sequence
158 
159           @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collateSQL_Latin1_General_CP850_Bin)
160 
161           IF @escape>0 --if there is one
162 
163             BEGIN
164 
165               WHILE @index<4 --there are always four digits to a \x sequence  
166 
167                 BEGIN
168 
169                   SELECT --determine its value
170 
171                     @result=@result+POWER(16, @index)
172 
173                     *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
174 
175                                 @characters)-1), @index=@index+1 ;
176 
177         
178 
179                 END
180 
181                 -- and replace the hex sequence by its unicode value
182 
183               SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
184 
185             END
186 
187         END
188 
189       --now store the string away
190 
191       INSERT INTO @Strings (StringValue) SELECT @token
192 
193       -- and replace the string with a token
194 
195       SELECT @JSON=STUFF(@json, @start, @end+1,
196 
197                     '@string'+CONVERT(NVARCHAR(5), @@identity))
198 
199     END
200 
201   -- all strings are now removed. Now we find the first leaf. 
202 
203   WHILE 1=1  --forever until there is nothing more to do
204 
205   BEGIN
206 
207  
208 
209   SELECT @parent_ID=@parent_ID+1
210 
211   --find the first object or list by looking for the open bracket
212 
213   SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array
214 
215   IF @FirstObject = 0 BREAK
216 
217   IF (SUBSTRING(@json, @FirstObject, 1)='{')
218 
219     SELECT @NextCloseDelimiterChar='}', @type='object'
220 
221   ELSE
222 
223     SELECT @NextCloseDelimiterChar=']', @type='array'
224 
225   SELECT @OpenDelimiter=@firstObject
226 
227  
228 
229   WHILE 1=1 --find the innermost object or list...
230 
231     BEGIN
232 
233       SELECT
234 
235         @lenJSON=LEN(@JSON+'|')-1
236 
237   --find the matching close-delimiter proceeding after the open-delimiter
238 
239       SELECT
240 
241         @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,
242 
243                                       @OpenDelimiter+1)
244 
245   --is there an intervening open-delimiter of either type
246 
247       SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
248 
249              RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
250 
251       IF @NextOpenDelimiter=0
252 
253         BREAK
254 
255       SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
256 
257       IF @NextCloseDelimiter<@NextOpenDelimiter
258 
259         BREAK
260 
261       IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{'
262 
263         SELECT @NextCloseDelimiterChar='}', @type='object'
264 
265       ELSE
266 
267         SELECT @NextCloseDelimiterChar=']', @type='array'
268 
269       SELECT @OpenDelimiter=@NextOpenDelimiter
270 
271     END
272 
273   ---and parse out the list or name/value pairs
274 
275   SELECT
276 
277     @contents=SUBSTRING(@json, @OpenDelimiter+1,
278 
279                         @NextCloseDelimiter-@OpenDelimiter-1)
280 
281   SELECT
282 
283     @JSON=STUFF(@json, @OpenDelimiter,
284 
285                 @NextCloseDelimiter-@OpenDelimiter+1,
286 
287                 '@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
288 
289   WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
290 
291     BEGIN
292 
293       IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
294 
295         BEGIN
296 
297           SELECT
298 
299             @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name.
300 
301           SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collateSQL_Latin1_General_CP850_Bin)--AAAAAAAA
302 
303           SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
304 
305             @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
306 
307             @param=RIGHT(@token, LEN(@token)-@endofname+1)
308 
309           SELECT
310 
311             @token=LEFT(@token, @endofname-1),
312 
313             @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
314 
315           SELECT  @name=stringvalue FROM @strings
316 
317             WHERE string_id=@param --fetch the name
318 
319         END
320 
321       ELSE
322 
323         SELECT @Name=null,@SequenceNo=@SequenceNo+1
324 
325       SELECT
326 
327         @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
328 
329       IF @end=0
330 
331         SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collateSQL_Latin1_General_CP850_Bin)
332 
333           +1
334 
335        SELECT
336 
337         @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collateSQL_Latin1_General_CP850_Bin)
338 
339       --select @start,@end, LEN(@contents+'|'), @contents 
340 
341       SELECT
342 
343         @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
344 
345         @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
346 
347       IF SUBSTRING(@value, 1, 7)='@object'
348 
349         INSERT INTO @hierarchy
350 
351           (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
352 
353           SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5),
354 
355             SUBSTRING(@value, 8, 5), 'object'
356 
357       ELSE
358 
359         IF SUBSTRING(@value, 1, 6)='@array'
360 
361           INSERT INTO @hierarchy
362 
363             (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
364 
365             SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5),
366 
367               SUBSTRING(@value, 7, 5), 'array'
368 
369         ELSE
370 
371           IF SUBSTRING(@value, 1, 7)='@string'
372 
373             INSERT INTO @hierarchy
374 
375               (NAME, SequenceNo, parent_ID, StringValue, ValueType)
376 
377               SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
378 
379               FROM @strings
380 
381               WHERE string_id=SUBSTRING(@value, 8, 5)
382 
383           ELSE
384 
385             IF @value IN ('true', 'false')
386 
387               INSERT INTO @hierarchy
388 
389                 (NAME, SequenceNo, parent_ID, StringValue, ValueType)
390 
391                 SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
392 
393             ELSE
394 
395               IF @value='null'
396 
397                 INSERT INTO @hierarchy
398 
399                   (NAME, SequenceNo, parent_ID, StringValue, ValueType)
400 
401                   SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
402 
403               ELSE
404 
405                 IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
406 
407                   INSERT INTO @hierarchy
408 
409                     (NAME, SequenceNo, parent_ID, StringValue, ValueType)
410 
411                     SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
412 
413                 ELSE
414 
415                   INSERT INTO @hierarchy
416 
417                     (NAME, SequenceNo, parent_ID, StringValue, ValueType)
418 
419                     SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
420 
421       if @Contents=' ' Select @SequenceNo=0
422 
423     END
424 
425   END
426 
427 INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
428 
429   SELECT '-',1, NULL, '', @parent_id-1, @type
430 
431 --
432 
433    RETURN
434 
435 END
436 
437 GO

 

So once we have a hierarchy, we can pass it to a stored procedure. As the output is an adjacency list, it should be easy to access the data. You might find it handy to create a table type if you are using SQL Server 2008. Here is what I use. (Note that if you drop a Table Valued Parameter type, you will have to drop any dependent functions or procedures first, and re-create them afterwards).

 1 -- Create the data type
 2 IF EXISTS (SELECT * FROM sys.types WHERE name LIKE 'Hierarchy')
 3 
 4   DROP TYPE dbo.Hierarchy
 5 
 6 go
 7 
 8 CREATE TYPE dbo.Hierarchy AS TABLE
 9 
10 (
11 
12    element_id INT NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */
13 
14    sequenceNo [int] NULL, /* the place in the sequence for the element */
15 
16    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 */
17 
18    [Object_ID] INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */
19 
20    NAME NVARCHAR(2000),/* the name of the object, null if it hasn't got one */
21 
22    StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */
23 
24    ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/
25 
26     PRIMARY KEY (element_id)
27 
28 )

 


ToJSON. A function that creates JSON Documents

Firstly, we need a simple utility function:

  1 IF OBJECT_ID (N'dbo.parseJSON') IS NOT NULL
  2    DROP FUNCTION dbo.JSONEscaped
  3 
  4 GO
  5 
  6  
  7 
  8 CREATE FUNCTION JSONEscaped ( /* this is a simple utility function that takes a SQL String with all its clobber and outputs it as a sting with all the JSON escape sequences in it.*/
  9 
 10   @Unescaped NVARCHAR(MAX) --a string with maybe characters that will break json
 11 
 12   )
 13 
 14 RETURNS NVARCHAR(MAX)
 15 
 16 AS
 17 
 18 BEGIN
 19 
 20   SELECT  @Unescaped = REPLACE(@Unescaped, FROMString, TOString)
 21 
 22   FROM    (SELECT
 23 
 24             '\"' AS FromString, '"' AS ToString
 25 
 26            UNION ALL SELECT '\', '\\'
 27 
 28            UNION ALL SELECT '/', '\/'
 29 
 30            UNION ALL SELECT  CHAR(08),'\b'
 31 
 32            UNION ALL SELECT  CHAR(12),'\f'
 33 
 34            UNION ALL SELECT  CHAR(10),'\n'
 35 
 36            UNION ALL SELECT  CHAR(13),'\r'
 37 
 38            UNION ALL SELECT  CHAR(09),'\t'
 39 
 40           ) substitutions
 41 
 42 RETURN @Unescaped
 43 
 44 END
 45 
 46 And now, the function that takes a JSON Hierarchy table and converts it to a JSON string.
 47 
 48 CREATE FUNCTION ToJSON
 49 
 50 (
 51 
 52       @Hierarchy Hierarchy READONLY
 53 
 54 )
 55 
 56  
 57 
 58 /*
 59 
 60 the function that takes a Hierarchy table and converts it to a JSON string
 61 
 62  
 63 
 64 Author: Phil Factor
 65 
 66 Revision: 1.5
 67 
 68 date: 1 May 2014
 69 
 70 why: Added a fix to add a name for a list.
 71 
 72 example:
 73 
 74  
 75 
 76 Declare @XMLSample XML
 77 
 78 Select @XMLSample='
 79 
 80   <glossary><title>example glossary</title>
 81 
 82   <GlossDiv><title>S</title>
 83 
 84    <GlossList>
 85 
 86     <GlossEntry ID="SGML" SortAs="SGML">
 87 
 88      <GlossTerm>Standard Generalized Markup Language</GlossTerm>
 89 
 90      <Acronym>SGML</Acronym>
 91 
 92      <Abbrev>ISO 8879:1986</Abbrev>
 93 
 94      <GlossDef>
 95 
 96       <para>A meta-markup language, used to create markup languages such as DocBook.</para>
 97 
 98       <GlossSeeAlso OtherTerm="GML" />
 99 
100       <GlossSeeAlso OtherTerm="XML" />
101 
102      </GlossDef>
103 
104      <GlossSee OtherTerm="markup" />
105 
106     </GlossEntry>
107 
108    </GlossList>
109 
110   </GlossDiv>
111 
112  </glossary>'
113 
114  
115 
116 DECLARE @MyHierarchy Hierarchy -- to pass the hierarchy table around
117 
118 insert into @MyHierarchy select * from dbo.ParseXML(@XMLSample)
119 
120 SELECT dbo.ToJSON(@MyHierarchy)
121 
122  
123 
124        */
125 
126 RETURNS NVARCHAR(MAX)--JSON documents are always unicode.
127 
128 AS
129 
130 BEGIN
131 
132   DECLARE
133 
134     @JSON NVARCHAR(MAX),
135 
136     @NewJSON NVARCHAR(MAX),
137 
138     @Where INT,
139 
140     @ANumber INT,
141 
142     @notNumber INT,
143 
144     @indent INT,
145 
146     @ii int,
147 
148     @CrLf CHAR(2)--just a simple utility to save typing!
149 
150      
151 
152   --firstly get the root token into place
153 
154   SELECT @CrLf=CHAR(13)+CHAR(10),--just CHAR(10) in UNIX
155 
156          @JSON = CASE ValueType WHEN 'array' THEN
157 
158          +COALESCE('{'+@CrLf+'  "'+NAME+'" : ','')+'['
159 
160          ELSE '{' END
161 
162             +@CrLf
163 
164             + case when ValueType='array' and NAME is not null then '  ' else '' end
165 
166             + '@Object'+CONVERT(VARCHAR(5),OBJECT_ID)
167 
168             +@CrLf+CASE ValueType WHEN 'array' THEN
169 
170             case when NAME is null then ']' else '  ]'+@CrLf+'}'+@CrLf end
171 
172                 ELSE '}' END
173 
174   FROM @Hierarchy
175 
176     WHERE parent_id IS NULL AND valueType IN ('object','document','array') --get the root element
177 
178 /* now we simply iterat from the root token growing each branch and leaf in each iteration. This won't be enormously quick, but it is simple to do. All values, or name/value pairs withing a structure can be created in one SQL Statement*/
179 
180   Select @ii=1000
181 
182   WHILE @ii>0
183 
184     begin
185 
186     SELECT @where= PATINDEX('%[^[a-zA-Z0-9]@Object%',@json)--find NEXT token
187 
188     if @where=0 BREAK
189 
190     /* this is slightly painful. we get the indent of the object we've found by looking backwards up the string */
191 
192     SET@indent=CHARINDEX(char(10)+char(13),Reverse(LEFT(@json,@where))+char(10)+char(13))-1
193 
194     SET @NotNumber= PATINDEX('%[^0-9]%', RIGHT(@json,LEN(@JSON+'|')-@Where-8)+' ')--find NEXT token
195 
196     SET @NewJSON=NULL --this contains the structure in its JSON form
197 
198     SELECT 
199 
200         @NewJSON=COALESCE(@NewJSON+','+@CrLf+SPACE(@indent),'')
201 
202         +case when parent.ValueType='array' then '' else COALESCE('"'+TheRow.NAME+'" : ','') end
203 
204         +CASE TheRow.valuetype
205 
206         WHEN 'array' THEN '  ['+@CrLf+SPACE(@indent+2)
207 
208            +'@Object'+CONVERT(VARCHAR(5),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+2)+']'
209 
210         WHEN 'object' then '  {'+@CrLf+SPACE(@indent+2)
211 
212            +'@Object'+CONVERT(VARCHAR(5),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+2)+'}'
213 
214         WHEN 'string' THEN '"'+dbo.JSONEscaped(TheRow.StringValue)+'"'
215 
216         ELSE TheRow.StringValue
217 
218        END
219 
220      FROM @Hierarchy TheRow
221 
222      inner join @hierarchy Parent
223 
224      on parent.element_ID=TheRow.parent_ID
225 
226       WHERE TheRow.parent_id= SUBSTRING(@JSON,@where+8, @Notnumber-1)
227 
228      /* basically, we just lookup the structure based on the ID that is appended to the @Object token. Simple eh? */
229 
230     --now we replace the token with the structure, maybe with more tokens in it.
231 
232     Select @JSON=STUFF (@JSON, @where+1, 8+@NotNumber-1, @NewJSON),@ii=@ii-1
233 
234     end
235 
236   return @JSON
237 
238 end
239 
240 go

 

 

ToXML. A function that creates XML

The function that converts a hierarchy  table to XML gives us a JSON to XML converter. It is surprisingly similar to the previous function

 

  1 IF OBJECT_ID (N'dbo.ToXML') IS NOT NULL
  2 
  3    DROP FUNCTION dbo.ToXML
  4 
  5 GO
  6 
  7 CREATE FUNCTION ToXML
  8 
  9 (
 10 
 11 /*this function converts a Hierarchy table into an XML document. This uses the same technique as the toJSON function, and uses the 'entities' form of XML syntax to give a compact rendering of the structure */
 12 
 13       @Hierarchy Hierarchy READONLY
 14 
 15 )
 16 
 17 RETURNS NVARCHAR(MAX)--use unicode.
 18 
 19 AS
 20 
 21 BEGIN
 22 
 23   DECLARE
 24 
 25     @XMLAsString NVARCHAR(MAX),
 26 
 27     @NewXML NVARCHAR(MAX),
 28 
 29     @Entities NVARCHAR(MAX),
 30 
 31     @Objects NVARCHAR(MAX),
 32 
 33     @Name NVARCHAR(200),
 34 
 35     @Where INT,
 36 
 37     @ANumber INT,
 38 
 39     @notNumber INT,
 40 
 41     @indent INT,
 42 
 43     @CrLf CHAR(2)--just a simple utility to save typing!
 44 
 45      
 46 
 47   --firstly get the root token into place
 48 
 49   --firstly get the root token into place
 50 
 51   SELECT @CrLf=CHAR(13)+CHAR(10),--just CHAR(10) in UNIX
 52 
 53          @XMLasString ='<?xml version="1.0" ?>
 54 
 55 @Object'+CONVERT(VARCHAR(5),OBJECT_ID)+'
 56 
 57 '
 58 
 59     FROM @hierarchy
 60 
 61     WHERE parent_id IS NULL AND valueType IN ('object','array') --get the root element
 62 
 63 /* now we simply iterate from the root token growing each branch and leaf in each iteration. This won't be enormously quick, but it is simple to do. All values, or name/value pairs within a structure can be created in one SQL Statement*/
 64 
 65   WHILE 1=1
 66 
 67     begin
 68 
 69     SELECT @where= PATINDEX('%[^a-zA-Z0-9]@Object%',@XMLAsString)--find NEXT token
 70 
 71     if @where=0 BREAK
 72 
 73     /* this is slightly painful. we get the indent of the object we've found by looking backwards up the string */
 74 
 75     SET@indent=CHARINDEX(char(10)+char(13),Reverse(LEFT(@XMLasString,@where))+char(10)+char(13))-1
 76 
 77     SET @NotNumber= PATINDEX('%[^0-9]%', RIGHT(@XMLasString,LEN(@XMLAsString+'|')-@Where-8)+' ')--find NEXT token
 78 
 79     SET @Entities=NULL --this contains the structure in its XML form
 80 
 81     SELECT @Entities=COALESCE(@Entities+' ',' ')+NAME+'="'
 82 
 83      +REPLACE(REPLACE(REPLACE(StringValue, '<', '&lt;'), '&', '&amp;'),'>', '&gt;')
 84 
 85      + '"' 
 86 
 87        FROM @hierarchy
 88 
 89        WHERE parent_id= SUBSTRING(@XMLasString,@where+8, @Notnumber-1)
 90 
 91           AND ValueType NOT IN ('array', 'object')
 92 
 93     SELECT @Entities=COALESCE(@entities,''),@Objects='',@name=CASE WHEN Name='-' THEN'root' ELSE NAME end
 94 
 95       FROM @hierarchy
 96 
 97       WHERE [Object_id]= SUBSTRING(@XMLasString,@where+8, @Notnumber-1)
 98 
 99    
100 
101     SELECT  @Objects=@Objects+@CrLf+SPACE(@indent+2)
102 
103            +'@Object'+CONVERT(VARCHAR(5),OBJECT_ID)
104 
105            --+@CrLf+SPACE(@indent+2)+''
106 
107       FROM @hierarchy
108 
109       WHERE parent_id= SUBSTRING(@XMLasString,@where+8, @Notnumber-1)
110 
111       AND ValueType IN ('array', 'object')
112 
113     IF @Objects='' --if it is a lef, we can do a more compact rendering
114 
115          SELECT @NewXML='<'+COALESCE(@name,'item')+@entities+' />'
116 
117     ELSE
118 
119         SELECT @NewXML='<'+COALESCE(@name,'item')+@entities+'>'
120 
121             +@Objects+@CrLf++SPACE(@indent)+'</'+COALESCE(@name,'item')+'>'
122 
123      /* basically, we just lookup the structure based on the ID that is appended to the @Object token. Simple eh? */
124 
125     --now we replace the token with the structure, maybe with more tokens in it.
126 
127     Select @XMLasString=STUFF (@XMLasString, @where+1, 8+@NotNumber-1, @NewXML)
128 
129     end
130 
131   return @XMLasString
132 
133   end

 

This provides you the means of converting a JSON string into XML

 1 DECLARE @MyHierarchy Hierarchy,@xml XML
 2 
 3 INSERT INTO @myHierarchy
 4 
 5 select * from parseJSON('{"menu": {
 6 
 7   "id": "file",
 8 
 9   "value": "File",
10 
11   "popup": {
12 
13     "menuitem": [
14 
15       {"value": "New", "onclick": "CreateNewDoc()"},
16 
17       {"value": "Open", "onclick": "OpenDoc()"},
18 
19       {"value": "Close", "onclick": "CloseDoc()"}
20 
21     ]
22 
23   }
24 
25 }}')
26 
27 SELECT dbo.ToXML(@MyHierarchy)
28 
29 SELECT @XML=dbo.ToXML(@MyHierarchy)
30 
31 SELECT @XML

 

This gives the result...

 

 1 <?xml version="1.0" ?>
 2 
 3 <root>
 4 
 5   <menu id="file" value="File">
 6 
 7     <popup>
 8 
 9       <menuitem>
10 
11         <item value="New" onclick="CreateNewDoc()" />
12 
13         <item value="Open" onclick="OpenDoc()" />
14 
15         <item value="Close" onclick="CloseDoc()" />
16 
17       </menuitem>
18 
19     </popup>
20 
21   </menu>
22 
23 </root>

 

(1 row(s) affected)

 1 <root>
 2   <menu id="file" value="File">
 3     <popup>
 4       <menuitem>
 5         <item value="New" onclick="CreateNewDoc()" />
 6         <item value="Open" onclick="OpenDoc()" />
 7         <item value="Close" onclick="CloseDoc()" />
 8       </menuitem>
 9     </popup>
10   </menu>
11 </root>

 

 

(1 row(s) affected)

 

来源: https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/

posted @ 2014-11-25 11:20  martin__zhu  阅读(1312)  评论(0)    收藏  举报