{"id":1026,"date":"2010-11-15T00:00:00","date_gmt":"2010-11-15T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/consuming-json-strings-in-sql-server\/"},"modified":"2026-03-09T13:39:09","modified_gmt":"2026-03-09T13:39:09","slug":"consuming-json-strings-in-sql-server","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/consuming-json-strings-in-sql-server\/","title":{"rendered":"Consume &#038; Query JSON in SQL Server with T-SQL"},"content":{"rendered":"<p>This article provides a T-SQL-based JSON parser and outputter for SQL Server, along with techniques for converting between JSON documents and relational table structures using an adjacency list representation. While SQL Server 2016+ includes built-in JSON functions (OPENJSON, JSON_VALUE, JSON_QUERY, FOR JSON), the custom parser approach demonstrated here works on older SQL Server versions and illustrates fundamental string-parsing techniques that remain valuable for understanding how JSON processing works under the hood. For the built-in JSON storage and indexing approach, see the companion article on storing and parsing JSON in SQL Server.<\/p>\n<p><em>Last updated 1st July 2019<\/em><\/p>\n<h4>Articles by Phil Factor about JSON and SQL Server:<\/h4>\n<ol>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/consuming-json-strings-in-sql-server\/\">Consuming JSON Strings in SQL Server (Nov 2012)<\/a> <\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/blogs\/sql-server-json-to-table-and-table-to-json\/\">SQL Server JSON to Table and Table to JSON (March 2013)<\/a>  <\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/producing-json-documents-from-sql-server-queries-via-tsql\/\">Producing JSON Documents From SQL Server Queries via TSQL (May 2014)<\/a>  <\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/blogs\/consuming-hierarchical-json-documents-sql-server-using-openjson\/\">Consuming hierarchical JSON documents in SQL Server using OpenJSON (Sept 2017)<\/a> <\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/importing-json-web-services-applications-sql-server\/\">Importing JSON data from Web Services and Applications into SQL Server(October 2017)<\/a> <\/li>\n<\/ol>\n\n<p><strong>Read also:<\/strong> <br \/><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/effective-strategies-for-storing-and-parsing-json-in-sql-server\/\" target=\"_blank\" rel=\"noopener\">Storing and indexing JSON in SQL Server<\/a><br \/><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/temporary-tables-in-sql-server\/\" target=\"_blank\" rel=\"noopener\">Temporary tables for staging parsed JSON output<\/a><\/p>\n<div id=\"pretty\">\n<div class=\"indent\">\n<p><i>&#8220;The best thing about XML is what it shares with JSON, being human readable. That turns out to be important, not because people should be reading it, because we shouldn&#8217;t, but because it avoids interoperability problems caused by fussy binary encoding issues. <\/i><\/p>\n<p>Beyond that, there is not much to like. It is not very good as a data format. And it is not very good as a document format. If it were a good document format, then wikis would use it.&#8221;<\/p>\n<p class=\"caption\">Doug Crockford <a href=\"https:\/\/www.red-gate.com\/simple-talk\/opinion\/geek-of-the-week\/doug-crockford-geek-of-the-week\/\">March 2010<\/a><\/p>\n<\/div>\n<p class=\"start\">This article describes a TSQL JSON parser and its evil twin, a JSON outputter, and provides the source. It is also designed to illustrate a number of string manipulation techniques in TSQL. With it you can do things like this to extract the data from a JSON document:<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">Select * from parseJSON('{  \u00a0 \"Person\": \n\u00a0 {\n\u00a0\u00a0\u00a0\u00a0 \"firstName\": \"John\",\n\u00a0\u00a0\u00a0\u00a0 \"lastName\": \"Smith\",\n\u00a0\u00a0\u00a0\u00a0 \"age\": 25,\n\u00a0\u00a0\u00a0\u00a0 \"Address\": \n\u00a0\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"streetAddress\":\"21 2nd Street\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"city\":\"New York\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"state\":\"NY\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"postalCode\":\"10021\"\n\u00a0\u00a0\u00a0\u00a0 },\n\u00a0\u00a0\u00a0\u00a0 \"PhoneNumbers\": \n\u00a0\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"home\":\"212 555-1234\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"fax\":\"646 555-4567\"\n\u00a0\u00a0\u00a0\u00a0 }\n\u00a0 }\n}\n')\n<\/pre>\n<p>And get:<\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1176-JSON1.jpg\" alt=\"1176-JSON1.jpg\" \/><\/p>\n<p>&#8230;or you can do the round trip:<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">DECLARE @MyHierarchy Hierarchy  INSERT INTO @myHierarchy \nselect * from parseJSON('{\"menu\": {\n\u00a0 \"id\": \"file\",\n\u00a0 \"value\": \"File\",\n\u00a0 \"popup\": {\n\u00a0\u00a0\u00a0 \"menuitem\": [\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n\u00a0\u00a0\u00a0 ]\n\u00a0 }\n}}')\nSELECT dbo.ToJSON(@MyHierarchy)\n<\/pre>\n<p>To get:<\/p>\n<pre>{  \"menu\" :\u00a0\u00a0 {\n\u00a0 \"id\" : \"file\",\n\u00a0 \"value\" : \"File\",\n\u00a0 \"popup\" :\u00a0\u00a0 {\n\u00a0\u00a0\u00a0 \"menuitem\" :\u00a0\u00a0 [\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\" : \"New\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"onclick\" : \"CreateNewDoc()\"\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 },\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\" : \"Open\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"onclick\" : \"OpenDoc()\"\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 },\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"value\" : \"Close\",\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \"onclick\" : \"CloseDoc()\"\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\u00a0\u00a0\u00a0\u00a0\u00a0 ]\n\u00a0\u00a0\u00a0 }\n\u00a0 }\n}\n<\/pre>\n<h1>Background<\/h1>\n<p>TSQL isn&#8217;t really designed for doing complex string parsing, particularly where strings represent nested data structures such as XML, JSON, YAML, or XHTML.\u00a0<\/p>\n<p>You can do it but it is not a pretty sight; but why would you ever want to do it anyway? Surely, if anything was meant for the &#8216;application layer&#8217; in C# or VB.net, then this is it. &#8216;Oh yes&#8217;, will chime in the application thought police, &#8216;this is far better done in the application or with a CLR.&#8217; Not necessarily.<\/p>\n<p>Sometimes, you just need to do something inappropriate in TSQL. (note: You can now do this rather more easily using SQL Server 2016&#8217;s built-in JSON support. See &#8216;<a href=\"https:\/\/www.red-gate.com\/simple-talk\/blogs\/consuming-hierarchical-json-documents-sql-server-using-openjson\/\">Consuming hierarchical JSON documents in SQL Server using OpenJSON<\/a>&#8216; which I wrote more recently)<\/p>\n<p>There are a whole lot of reasons why this might happen to you. It could be that your DBA doesn&#8217;t allow a CLR, for example, or you lack the necessary skills with procedural code. Sometimes, there isn&#8217;t any application, or you want to run code unobtrusively across databases or servers.<\/p>\n<p>I needed to interpret or &#8216;shred&#8217; JSON data. JSON is one of the most popular lightweight markup languages, and is probably the best choice for transfer of object data from a web page. It is, in fact, executable JavaScript that is very quick to code in the browser in order to dump the contents of a JavaScript object, and is lightning-fast to populate the browser object from the database since you are passing it executable code (you need to parse it first for security reasons &#8211; passing executable code around is potentially very risky). AJAX can use JSON rather than XML so you have an opportunity to have a much simpler route for data between database and browser, with less opportunity for error.<\/p>\n<p>The conventional way of dealing with data like this is to let a separate business layer parse a JSON &#8216;document&#8217; into some tree structure and then update the database by making a series of calls to it. This is fine, but can get more complicated if you need to ensure that the updates to the database are wrapped into one transaction so that if anything goes wrong, then the whole operation can be rolled back. This is why a CLR or TSQL approach has advantages.<\/p>\n<p class=\"quote\">&#8220;Sometimes, you just <br \/>need to do something <br \/>inappropriate in TSQL&#8230;&#8221;<\/p>\n<p>I wrote the parser as a prototype because it was the quickest way to determine what was involved in the process, so I could then re-write something as a CLR in a .NET language.\u00a0 It takes a JSON string and produces a result in the form of an adjacency list representation of that hierarchy. In the end, the code did what I wanted with adequate performance (It reads a json file of \u00a0540 name\\value pairs and creates the SQL \u00a0hierarchy table \u00a0in 4 seconds) so I didn&#8217;t bother with the added complexity of maintaining a CLR routine. In order to test more thoroughly what I&#8217;d done, I wrote a JSON generator that used the same Adjacency list, so you can now import and export data via JSON!<\/p>\n<p>These markup languages such as JSON and XML all represent object data as hierarchies. Although it looks very different to the entity-relational model, it isn&#8217;t. It is rather more a different perspective on the same model. The first trick is to represent it as a Adjacency list hierarchy in a table, and then use the contents of this table to update the database. This Adjacency list is really the Database equivalent of any of the nested data structures that are used for the interchange of serialized information with the application, and can be used to create XML, OSX Property lists, Python nested structures or YAML as easily as JSON.<\/p>\n<p>Adjacency list tables have the same structure whatever the data in them. This means that you can define a single Table-Valued\u00a0 Type and pass data structures around between stored procedures. However, they are best held at arms-length from the data, since they are not relational tables, but something more like the dreaded EAV (Entity-Attribute-Value) tables. Converting the data from its Hierarchical table form will be different for each application, but is easy with a CTE. You can, alternatively, convert the hierarchical table into XML and interrogate that with XQuery.<\/p>\n<h1>JSON format.<\/h1>\n<p>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 <i>object<\/i>, 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 <i>array<\/i>, vector, list, or sequence.<\/p>\n<p class=\"quote\">&#8220;Using recursion in TSQL is <br \/>like Sumo Wrestlers doing Ballet. <br \/>It is possible but not pretty.&#8221;<\/p>\n<p>The first snag for TSQL is that the curly or square brackets are not &#8216;escaped&#8217; within a string, so that there is no way of shredding a JSON &#8216;document&#8217; simply. It is difficult to\u00a0 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&#8217;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&#8217;t be explicitly declared. You have to sniff them out from applying the rules from the <a href=\"http:\/\/www.ietf.org\/rfc\/rfc4627.txt?number=4627\">JSON Specification<\/a>.<\/p>\n<p>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.<\/p>\n<h1>The implementation<\/h1>\n<p>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&#8217;t resist using a TVP (Table Valued Parameter) to pass a hierarchical table to the function, <b>ToJSON,<\/b> that produces a JSON &#8216;document&#8217;. Writing a SQL Server 2005 version should not be too hard.<\/p>\n<p>First the function replaces all strings with tokens of the form <strong>@Stringxx<\/strong>, where <strong>xx<\/strong> 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\u00a0 always strings in JSON as well as\u00a0 string values.<\/p>\n<p>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 &#8216;<strong>@Objectxxx<\/strong>&#8216;, or &#8216;<strong>@arrayxxx<\/strong>&#8216;, where <strong>xxx<\/strong> is 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.<\/p>\n<p>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.<\/p>\n<p>In the implementation, you&#8217;ll see a fairly heavy use of PATINDEX. This uses a poor man&#8217;s RegEx, a starving man&#8217;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.<\/p>\n<pre class=\"theme:ssms2012 font-size:14 lang:tsql decode:true \">Alter FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX))\n\/**\nSummary: &gt;\n  The code for the JSON Parser\/Shredder will run in SQL Server 2005, \n  and even in SQL Server 2000 (with some modifications required).\n\n  First the function replaces all strings with tokens of the form @Stringxx,\n  where xx is the foreign key of the table variable where the strings are held.\n  This takes them, and their potentially difficult embedded brackets, out of \n  the way. Names are  always strings in JSON as well as  string values.\n\n  Then, the routine iteratively finds the next structure that has no structure \n  Contained within it, (and is, by definition the leaf structure), and parses it,\n  replacing it with an object token of the form \u2018@Objectxxx\u2018, or \u2018@arrayxxx\u2018, \n  where xxx is the object id assigned to it. The values, or name\/value pairs \n  are retrieved from the string table and stored in the hierarchy table. G\n  radually, the JSON document is eaten until there is just a single root\n  object left.\nAuthor: PhilFactor\nDate: 01\/07\/2010\nVersion: \n  Number: 4.6.2\n  Date: 01\/07\/2019\n  Why: case-insensitive version\nExample: &gt;\n  Select * from parseJSON('{    \"Person\": \n      {\n       \"firstName\": \"John\",\n       \"lastName\": \"Smith\",\n       \"age\": 25,\n       \"Address\": \n           {\n          \"streetAddress\":\"21 2nd Street\",\n          \"city\":\"New York\",\n          \"state\":\"NY\",\n          \"postalCode\":\"10021\"\n           },\n       \"PhoneNumbers\": \n           {\n           \"home\":\"212 555-1234\",\n          \"fax\":\"646 555-4567\"\n           }\n        }\n     }\n  ')\nReturns: &gt;\n  nothing\n**\/\n\tRETURNS @hierarchy TABLE\n\t  (\n\t   Element_ID INT IDENTITY(1, 1) NOT NULL, \/* internal surrogate primary key gives the order of parsing and the list order *\/\n\t   SequenceNo [int] NULL, \/* the place in the sequence for the element *\/\n\t   Parent_ID INT null, \/* 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 *\/\n\t   Object_ID INT null, \/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here *\/\n\t   Name NVARCHAR(2000) NULL, \/* the Name of the object *\/\n\t   StringValue NVARCHAR(MAX) NOT NULL,\/*the string representation of the value of the element. *\/\n\t   ValueType VARCHAR(10) NOT null \/* the declared type of the value represented as a string in StringValue*\/\n\t  )\n\t  \/*\n\n\t   *\/\n\tAS\n\tBEGIN\n\t  DECLARE\n\t    @FirstObject INT, --the index of the first open bracket found in the JSON string\n\t    @OpenDelimiter INT,--the index of the next open bracket found in the JSON string\n\t    @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string\n\t    @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string\n\t    @Type NVARCHAR(10),--whether it denotes an object or an array\n\t    @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'\n\t    @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression\n\t    @Start INT, --index of the start of the token that you are parsing\n\t    @end INT,--index of the end of the token that you are parsing\n\t    @param INT,--the parameter at the end of the next Object\/Array token\n\t    @EndOfName INT,--the index of the start of the parameter at end of Object\/Array token\n\t    @token NVARCHAR(200),--either a string or object\n\t    @value NVARCHAR(MAX), -- the value as a string\n\t    @SequenceNo int, -- the sequence number within a list\n\t    @Name NVARCHAR(200), --the Name as a string\n\t    @Parent_ID INT,--the next parent ID to allocate\n\t    @lenJSON INT,--the current length of the JSON String\n\t    @characters NCHAR(36),--used to convert hex to decimal\n\t    @result BIGINT,--the value of the hex symbol being parsed\n\t    @index SMALLINT,--used for parsing the hex value\n\t    @Escape INT --the index of the next escape character\n\t    \n\t  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 *\/\n\t    (\n\t     String_ID INT IDENTITY(1, 1),\n\t     StringValue NVARCHAR(MAX)\n\t    )\n\t  SELECT--initialise the characters to convert hex to ascii\n\t    @characters='0123456789abcdefghijklmnopqrstuvwxyz',\n\t    @SequenceNo=0, --set the sequence no. to something sensible.\n\t  \/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. *\/\n\t    @Parent_ID=0;\n\t  WHILE 1=1 --forever until there is nothing more to do\n\t    BEGIN\n\t      SELECT\n\t        @start=PATINDEX('%[^a-zA-Z][\"]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string\n\t      IF @start=0 BREAK --no more so drop through the WHILE loop\n\t      IF SUBSTRING(@json, @start+1, 1)='\"' \n\t        BEGIN --Delimited Name\n\t          SET @start=@Start+1;\n\t          SET @end=PATINDEX('%[^\\][\"]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);\n\t        END\n\t      IF @end=0 --either the end or no end delimiter to last string\n\t        BEGIN-- check if ending with a double slash...\n             SET @end=PATINDEX('%[\\][\\][\"]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin);\n \t\t     IF @end=0 --we really have reached the end \n\t\t\t\tBEGIN\n\t\t\t\tBREAK --assume all tokens found\n\t\t\t\tEND\n\t\t\tEND \n\t      SELECT @token=SUBSTRING(@json, @start+1, @end-1)\n\t      --now put in the escaped control characters\n\t      SELECT @token=REPLACE(@token, FromString, ToString)\n\t      FROM\n\t        (SELECT           '\\b', CHAR(08)\n\t         UNION ALL SELECT '\\f', CHAR(12)\n\t         UNION ALL SELECT '\\n', CHAR(10)\n\t         UNION ALL SELECT '\\r', CHAR(13)\n\t         UNION ALL SELECT '\\t', CHAR(09)\n\t\t\t UNION ALL SELECT '\\\"', '\"'\n\t         UNION ALL SELECT '\\\/', '\/'\n\t        ) substitutions(FromString, ToString)\n\t\tSELECT @token=Replace(@token, '\\\\', '\\')\n\t      SELECT @result=0, @escape=1\n\t  --Begin to take out any hex escape codes\n\t      WHILE @escape&gt;0\n\t        BEGIN\n\t          SELECT @index=0,\n\t          --find the next hex escape sequence\n\t          @escape=PATINDEX('%\\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)\n\t          IF @escape&gt;0 --if there is one\n\t            BEGIN\n\t              WHILE @index&lt;4 --there are always four digits to a \\x sequence   \n\t                BEGIN\n\t                  SELECT --determine its value\n\t                    @result=@result+POWER(16, @index)\n\t                    *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),\n\t                                @characters)-1), @index=@index+1 ;\n\t         \n\t                END\n\t                -- and replace the hex sequence by its unicode value\n\t              SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))\n\t            END\n\t        END\n\t      --now store the string away \n\t      INSERT INTO @Strings (StringValue) SELECT @token\n\t      -- and replace the string with a token\n\t      SELECT @JSON=STUFF(@json, @start, @end+1,\n\t                    '@string'+CONVERT(NCHAR(5), @@identity))\n\t    END\n\t  -- all strings are now removed. Now we find the first leaf.  \n\t  WHILE 1=1  --forever until there is nothing more to do\n\t  BEGIN\n\t \n\t  SELECT @Parent_ID=@Parent_ID+1\n\t  --find the first object or list by looking for the open bracket\n\t  SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array\n\t  IF @FirstObject = 0 BREAK\n\t  IF (SUBSTRING(@json, @FirstObject, 1)='{') \n\t    SELECT @NextCloseDelimiterChar='}', @type='object'\n\t  ELSE \n\t    SELECT @NextCloseDelimiterChar=']', @type='array'\n\t  SELECT @OpenDelimiter=@firstObject\n\t  WHILE 1=1 --find the innermost object or list...\n\t    BEGIN\n\t      SELECT\n\t        @lenJSON=LEN(@JSON+'|')-1\n\t  --find the matching close-delimiter proceeding after the open-delimiter\n\t      SELECT\n\t        @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json,\n\t                                      @OpenDelimiter+1)\n\t  --is there an intervening open-delimiter of either type\n\t      SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',\n\t             RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object\n\t      IF @NextOpenDelimiter=0 \n\t        BREAK\n\t      SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter\n\t      IF @NextCloseDelimiter&lt;@NextOpenDelimiter \n\t        BREAK\n\t      IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{' \n\t        SELECT @NextCloseDelimiterChar='}', @type='object'\n\t      ELSE \n\t        SELECT @NextCloseDelimiterChar=']', @type='array'\n\t      SELECT @OpenDelimiter=@NextOpenDelimiter\n\t    END\n\t  ---and parse out the list or Name\/value pairs\n\t  SELECT\n\t    @contents=SUBSTRING(@json, @OpenDelimiter+1,\n\t                        @NextCloseDelimiter-@OpenDelimiter-1)\n\t  SELECT\n\t    @JSON=STUFF(@json, @OpenDelimiter,\n\t                @NextCloseDelimiter-@OpenDelimiter+1,\n\t                '@'+@type+CONVERT(NCHAR(5), @Parent_ID))\n\t  WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))&lt;&gt;0 \n\t    BEGIN\n\t      IF @Type='object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null\n\t        BEGIN\n\t          SELECT\n\t            @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based Name.\n\t          SELECT  @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA\n              SELECT @token=RTrim(Substring(' '+@contents, @start+1, @End-@Start-1)),\n\t            @endofName=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),\n\t            @param=RIGHT(@token, LEN(@token)-@endofName+1)\n\t          SELECT\n\t            @token=LEFT(@token, @endofName-1),\n\t            @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)\n\t          SELECT  @Name=StringValue FROM @strings\n\t            WHERE string_id=@param --fetch the Name\n\t        END\n\t      ELSE \n\t        SELECT @Name=null,@SequenceNo=@SequenceNo+1 \n\t      SELECT\n\t        @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null\n                IF @end=0\n\t        --HR Engineering notation bugfix start\n\t          IF ISNUMERIC(@contents) = 1\n\t\t    SELECT @end = LEN(@contents) + 1\n\t          Else\n\t        --HR Engineering notation bugfix end \n\t\t  SELECT  @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @contents+' ' collate SQL_Latin1_General_CP850_Bin) + 1\n\t       SELECT\n\t        @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)\n\t      --select @start,@end, LEN(@contents+'|'), @contents  \n\t      SELECT\n\t        @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),\n\t        @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)\n\t      IF SUBSTRING(@value, 1, 7)='@object' \n\t        INSERT INTO @hierarchy\n\t          (Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType)\n\t          SELECT @Name, @SequenceNo, @Parent_ID, SUBSTRING(@value, 8, 5),\n\t            SUBSTRING(@value, 8, 5), 'object' \n\t      ELSE \n\t        IF SUBSTRING(@value, 1, 6)='@array' \n\t          INSERT INTO @hierarchy\n\t            (Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType)\n\t            SELECT @Name, @SequenceNo, @Parent_ID, SUBSTRING(@value, 7, 5),\n\t              SUBSTRING(@value, 7, 5), 'array' \n\t        ELSE \n\t          IF SUBSTRING(@value, 1, 7)='@string' \n\t            INSERT INTO @hierarchy\n\t              (Name, SequenceNo, Parent_ID, StringValue, ValueType)\n\t              SELECT @Name, @SequenceNo, @Parent_ID, StringValue, 'string'\n\t              FROM @strings\n\t              WHERE string_id=SUBSTRING(@value, 8, 5)\n\t          ELSE \n\t            IF @value IN ('true', 'false') \n\t              INSERT INTO @hierarchy\n\t                (Name, SequenceNo, Parent_ID, StringValue, ValueType)\n\t                SELECT @Name, @SequenceNo, @Parent_ID, @value, 'boolean'\n\t            ELSE\n\t              IF @value='null' \n\t                INSERT INTO @hierarchy\n\t                  (Name, SequenceNo, Parent_ID, StringValue, ValueType)\n\t                  SELECT @Name, @SequenceNo, @Parent_ID, @value, 'null'\n\t              ELSE\n\t                IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)&gt;0 \n\t                  INSERT INTO @hierarchy\n\t                    (Name, SequenceNo, Parent_ID, StringValue, ValueType)\n\t                    SELECT @Name, @SequenceNo, @Parent_ID, @value, 'real'\n\t                ELSE\n\t                  INSERT INTO @hierarchy\n\t                    (Name, SequenceNo, Parent_ID, StringValue, ValueType)\n\t                    SELECT @Name, @SequenceNo, @Parent_ID, @value, 'int'\n\t      if @Contents=' ' Select @SequenceNo=0\n\t    END\n\t  END\n\tINSERT INTO @hierarchy (Name, SequenceNo, Parent_ID, StringValue, Object_ID, ValueType)\n\t  SELECT '-',1, NULL, '', @Parent_ID-1, @type\n\t--\n\t   RETURN\n\tEND\nGO<\/pre>\n<p>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).<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">-- Create the data type  IF EXISTS (SELECT * FROM sys.types WHERE name LIKE 'Hierarchy')\n\u00a0 DROP TYPE dbo.Hierarchy\ngo\nCREATE TYPE dbo.Hierarchy AS TABLE\n(\n\u00a0\u00a0 element_id INT NOT NULL, \/* internal surrogate primary key gives the order of parsing and the list order *\/\n\u00a0\u00a0 sequenceNo [int] NULL, \/* the place in the sequence for the element *\/\n\t\u00a0\u00a0 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 *\/\n\u00a0\u00a0 [Object_ID] INT,\/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here *\/\n\u00a0\u00a0 NAME NVARCHAR(2000),\/* the name of the object, null if it hasn't got one *\/\n\u00a0\u00a0 StringValue NVARCHAR(MAX) NOT NULL,\/*the string representation of the value of the element. *\/\n\u00a0\u00a0 ValueType VARCHAR(10) NOT null \/* the declared type of the value represented as a string in StringValue*\/\n\u00a0\u00a0\u00a0 PRIMARY KEY (element_id)\n)\n<\/pre>\n<h1>ToJSON. A function that creates JSON Documents<\/h1>\n<p>Firstly, we need a simple utility function:<\/p>\n<pre class=\"theme:ssms2012 lang:tsql \">IF OBJECT_ID (N'dbo.JSONEscaped') IS NOT NULL  \u00a0\u00a0 DROP FUNCTION dbo.JSONEscaped\nGO\n\nCREATE FUNCTION [dbo].[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.*\/\n @Unescaped NVARCHAR(MAX) --a string with maybe characters that will break json\n )\nRETURNS NVARCHAR(MAX)\nAS\nBEGIN\n  SELECT @Unescaped = REPLACE(@Unescaped, FROMString, TOString)\n  FROM (SELECT '' AS FromString, '\\' AS ToString \n        UNION ALL SELECT '\"', '\"' \n        UNION ALL SELECT '\/', '\/'\n        UNION ALL SELECT CHAR(08),'b'\n        UNION ALL SELECT CHAR(12),'f'\n        UNION ALL SELECT CHAR(10),'n'\n        UNION ALL SELECT CHAR(13),'r'\n        UNION ALL SELECT CHAR(09),'t'\n ) substitutions\nRETURN @Unescaped\nEND\nGO\n\n<\/pre>\n<p>And now, the function that takes a JSON Hierarchy table and converts it to a JSON string.<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">\tCREATE FUNCTION ToJSON\n\t(\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 @Hierarchy Hierarchy READONLY\n\t)\n\t\u00a0\n\t\/*\n\tthe function that takes a Hierarchy table and converts it to a JSON string\n\t\u00a0\n\tAuthor: Phil Factor\n\tRevision: 1.5\n\tdate: 1 May 2014\n\twhy: Added a fix to add a name for a list.\n\texample:\n\t\u00a0\n\tDeclare @XMLSample XML\n\tSelect @XMLSample='\n\t\u00a0 &lt;glossary&gt;&lt;title&gt;example glossary&lt;\/title&gt;\n\t\u00a0 &lt;GlossDiv&gt;&lt;title&gt;S&lt;\/title&gt;\n\t\u00a0\u00a0 &lt;GlossList&gt;\n\t\u00a0\u00a0\u00a0 &lt;GlossEntry id=\"SGML\"\" SortAs=\"SGML\"&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;GlossTerm&gt;Standard Generalized Markup Language&lt;\/GlossTerm&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;Acronym&gt;SGML&lt;\/Acronym&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;Abbrev&gt;ISO 8879:1986&lt;\/Abbrev&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;GlossDef&gt;\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;para&gt;A meta-markup language, used to create markup languages such as DocBook.&lt;\/para&gt;\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;GlossSeeAlso OtherTerm=\"GML\" \/&gt;\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;GlossSeeAlso OtherTerm=\"XML\" \/&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;\/GlossDef&gt;\n\t\u00a0\u00a0\u00a0\u00a0 &lt;GlossSee OtherTerm=\"markup\" \/&gt;\n\t\u00a0\u00a0\u00a0 &lt;\/GlossEntry&gt;\n\t\u00a0\u00a0 &lt;\/GlossList&gt;\n\t\u00a0 &lt;\/GlossDiv&gt;\n\t\u00a0&lt;\/glossary&gt;'\n\t\u00a0\n\tDECLARE @MyHierarchy Hierarchy -- to pass the hierarchy table around\n\tinsert into @MyHierarchy select * from dbo.ParseXML(@XMLSample)\n\tSELECT dbo.ToJSON(@MyHierarchy)\n\t\u00a0\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 *\/\n\tRETURNS NVARCHAR(MAX)--JSON documents are always unicode.\n\tAS\n\tBEGIN\n\t\u00a0 DECLARE\n\t\u00a0\u00a0\u00a0 @JSON NVARCHAR(MAX),\n\t\u00a0\u00a0\u00a0 @NewJSON NVARCHAR(MAX),\n\t\u00a0\u00a0\u00a0 @Where INT,\n\t\u00a0\u00a0\u00a0 @ANumber INT,\n\t\u00a0\u00a0\u00a0 @notNumber INT,\n\t\u00a0\u00a0\u00a0 @indent INT,\n\t\u00a0\u00a0\u00a0 @ii int,\n\t\u00a0\u00a0\u00a0 @CrLf CHAR(2)--just a simple utility to save typing!\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 \n\t\u00a0 --firstly get the root token into place \n\t\u00a0 SELECT @CrLf=CHAR(13)+CHAR(10),--just CHAR(10) in UNIX\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 @JSON = CASE ValueType WHEN 'array' THEN \n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +COALESCE('{'+@CrLf+'\u00a0 \"'+NAME+'\" : ','')+'[' \n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ELSE '{' END\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +@CrLf\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 + case when ValueType='array' and NAME is not null then '\u00a0 ' else '' end\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 + '@Object'+CONVERT(VARCHAR(5),OBJECT_ID)\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +@CrLf+CASE ValueType WHEN 'array' THEN\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 case when NAME is null then ']' else '\u00a0 ]'+@CrLf+'}'+@CrLf end\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ELSE '}' END\n\t\u00a0 FROM @Hierarchy \n\t\u00a0\u00a0\u00a0 WHERE parent_id IS NULL AND valueType IN ('object','document','array') --get the root element\n\t\/* 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*\/\n\t\u00a0 Select @ii=1000\n\t\u00a0 WHILE @ii&gt;0\n\t\u00a0\u00a0\u00a0 begin\n\t\u00a0\u00a0\u00a0 SELECT @where= PATINDEX('%[^[a-zA-Z0-9]@Object%',@json)--find NEXT token\n\t\u00a0\u00a0\u00a0 if @where=0 BREAK\n\t\u00a0\u00a0\u00a0 \/* this is slightly painful. we get the indent of the object we've found by looking backwards up the string *\/ \n\t\u00a0\u00a0\u00a0 SET @indent=CHARINDEX(char(10)+char(13),Reverse(LEFT(@json,@where))+char(10)+char(13))-1\n\t\u00a0\u00a0\u00a0 SET @NotNumber= PATINDEX('%[^0-9]%', RIGHT(@json,LEN(@JSON+'|')-@Where-8)+' ')--find NEXT token\n\t\u00a0\u00a0\u00a0 SET @NewJSON=NULL --this contains the structure in its JSON form\n\t\u00a0\u00a0\u00a0 SELECT\u00a0 \n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 @NewJSON=COALESCE(@NewJSON+','+@CrLf+SPACE(@indent),'')\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +case when parent.ValueType='array' then '' else COALESCE('\"'+TheRow.NAME+'\" : ','') end\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +CASE TheRow.valuetype\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WHEN 'array' THEN '\u00a0 ['+@CrLf+SPACE(@indent+2)\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +'@Object'+CONVERT(VARCHAR(5),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+2)+']' \n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WHEN 'object' then '\u00a0 {'+@CrLf+SPACE(@indent+2)\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +'@Object'+CONVERT(VARCHAR(5),TheRow.[OBJECT_ID])+@CrLf+SPACE(@indent+2)+'}'\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WHEN 'string' THEN '\"'+dbo.JSONEscaped(TheRow.StringValue)+'\"'\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ELSE TheRow.StringValue\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 END \n\t\u00a0\u00a0\u00a0\u00a0 FROM @Hierarchy TheRow \n\t\u00a0\u00a0\u00a0\u00a0 inner join @hierarchy Parent\n\t\u00a0\u00a0\u00a0\u00a0 on parent.element_ID=TheRow.parent_ID\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 WHERE TheRow.parent_id= SUBSTRING(@JSON,@where+8, @Notnumber-1)\n\t\u00a0\u00a0\u00a0\u00a0 \/* basically, we just lookup the structure based on the ID that is appended to the @Object token. Simple eh? *\/\n\t\u00a0\u00a0\u00a0 --now we replace the token with the structure, maybe with more tokens in it.\n\t\u00a0\u00a0\u00a0 Select @JSON=STUFF (@JSON, @where+1, 8+@NotNumber-1, @NewJSON),@ii=@ii-1\n\t\u00a0\u00a0\u00a0 end\n\t\u00a0 return @JSON\n\tend\n\tgo\n\t<\/pre>\n<h1>ToXML. A function that creates XML<\/h1>\n<p>The function that converts a hierarchy\u00a0 table to XML gives us a JSON to XML converter. It is surprisingly similar to the previous function<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">\u00a0\nIF OBJECT_ID (N'dbo.ToXML') IS NOT NULL\n\u00a0\u00a0 DROP FUNCTION dbo.ToXML\nGO\nCREATE FUNCTION ToXML\n(\n\/*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 *\/\n\u00a0\u00a0\u00a0\u00a0\u00a0 @Hierarchy Hierarchy READONLY\n)\nRETURNS NVARCHAR(MAX)--use unicode.\nAS\nBEGIN\n\u00a0 DECLARE\n\u00a0\u00a0\u00a0 @XMLAsString NVARCHAR(MAX),\n\u00a0\u00a0\u00a0 @NewXML NVARCHAR(MAX),\n\u00a0\u00a0\u00a0 @Entities NVARCHAR(MAX),\n\u00a0\u00a0\u00a0 @Objects NVARCHAR(MAX),\n\u00a0\u00a0\u00a0 @Name NVARCHAR(200),\n\u00a0\u00a0\u00a0 @Where INT,\n\u00a0\u00a0\u00a0 @ANumber INT,\n\u00a0\u00a0\u00a0 @notNumber INT,\n\u00a0\u00a0\u00a0 @indent INT,\n\u00a0\u00a0\u00a0 @CrLf CHAR(2)--just a simple utility to save typing!\n\u00a0\u00a0\u00a0\u00a0\u00a0 \n\u00a0 --firstly get the root token into place \n\u00a0 --firstly get the root token into place \n\u00a0 SELECT @CrLf=CHAR(13)+CHAR(10),--just CHAR(10) in UNIX\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 @XMLasString ='&lt;?xml version=\"1.0\" ?&gt;\n@Object'+CONVERT(VARCHAR(5),OBJECT_ID)+'\n'\n\u00a0\u00a0\u00a0 FROM @hierarchy \n\u00a0\u00a0\u00a0 WHERE parent_id IS NULL AND valueType IN ('object','array') --get the root element\n\/* 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*\/\n\u00a0 WHILE 1=1\n\u00a0\u00a0\u00a0 begin\n\u00a0\u00a0\u00a0 SELECT @where= PATINDEX('%[^a-zA-Z0-9]@Object%',@XMLAsString)--find NEXT token\n\u00a0\u00a0\u00a0 if @where=0 BREAK\n\u00a0\u00a0\u00a0 \/* this is slightly painful. we get the indent of the object we've found by looking backwards up the string *\/ \n\u00a0\u00a0\u00a0 SET @indent=CHARINDEX(char(10)+char(13),Reverse(LEFT(@XMLasString,@where))+char(10)+char(13))-1\n\u00a0\u00a0\u00a0 SET @NotNumber= PATINDEX('%[^0-9]%', RIGHT(@XMLasString,LEN(@XMLAsString+'|')-@Where-8)+' ')--find NEXT token\n\u00a0\u00a0\u00a0 SET @Entities=NULL --this contains the structure in its XML form\n\u00a0\u00a0\u00a0 SELECT @Entities=COALESCE(@Entities+' ',' ')+NAME+'=\"'\n\u00a0\u00a0\u00a0\u00a0 +REPLACE(REPLACE(REPLACE(StringValue, '&lt;', '&amp;lt;'), '&amp;', '&amp;amp;'),'&gt;', '&amp;gt;')\n\u00a0\u00a0\u00a0\u00a0 + '\"'\u00a0 \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 FROM @hierarchy \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WHERE parent_id= SUBSTRING(@XMLasString,@where+8, @Notnumber-1) \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 AND ValueType NOT IN ('array', 'object')\n\u00a0\u00a0\u00a0 SELECT @Entities=COALESCE(@entities,''),@Objects='',@name=CASE WHEN Name='-' THEN 'root' ELSE NAME end\n\u00a0\u00a0\u00a0\u00a0\u00a0 FROM @hierarchy \n\u00a0\u00a0\u00a0\u00a0\u00a0 WHERE [Object_id]= SUBSTRING(@XMLasString,@where+8, @Notnumber-1) \n\u00a0\u00a0\u00a0 \n\u00a0\u00a0\u00a0 SELECT\u00a0 @Objects=@Objects+@CrLf+SPACE(@indent+2)\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +'@Object'+CONVERT(VARCHAR(5),OBJECT_ID)\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 --+@CrLf+SPACE(@indent+2)+''\n\u00a0\u00a0\u00a0\u00a0\u00a0 FROM @hierarchy \n\u00a0\u00a0\u00a0\u00a0\u00a0 WHERE parent_id= SUBSTRING(@XMLasString,@where+8, @Notnumber-1) \n\u00a0\u00a0\u00a0\u00a0\u00a0 AND ValueType IN ('array', 'object')\n\u00a0\u00a0\u00a0 IF @Objects='' --if it is a lef, we can do a more compact rendering\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT @NewXML='&lt;'+COALESCE(@name,'item')+@entities+' \/&gt;'\n\u00a0\u00a0\u00a0 ELSE\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 SELECT @NewXML='&lt;'+COALESCE(@name,'item')+@entities+'&gt;'\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 +@Objects+@CrLf++SPACE(@indent)+'&lt;\/'+COALESCE(@name,'item')+'&gt;'\n\u00a0\u00a0\u00a0\u00a0 \/* basically, we just lookup the structure based on the ID that is appended to the @Object token. Simple eh? *\/\n\u00a0\u00a0\u00a0 --now we replace the token with the structure, maybe with more tokens in it.\n\u00a0\u00a0\u00a0 Select @XMLasString=STUFF (@XMLasString, @where+1, 8+@NotNumber-1, @NewXML)\n\u00a0\u00a0\u00a0 end\n\u00a0 return @XMLasString\n\u00a0 end\n<\/pre>\n<p>This provides you the means of converting a JSON string into XML<\/p>\n<pre class=\"theme:ssms2012 lang:tsql\">DECLARE @MyHierarchy Hierarchy,@xml XML\nINSERT INTO @myHierarchy \nselect * from parseJSON('{\"menu\": {\n\u00a0 \"id\": \"file\",\n\u00a0 \"value\": \"File\",\n\u00a0 \"popup\": {\n\u00a0\u00a0\u00a0 \"menuitem\": [\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n\u00a0\u00a0\u00a0\u00a0\u00a0 {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n\u00a0\u00a0\u00a0 ]\n\u00a0 }\n}}')\nSELECT dbo.ToXML(@MyHierarchy)\nSELECT @XML=dbo.ToXML(@MyHierarchy)\nSELECT @XML\n<\/pre>\n<p>This gives the result&#8230;<\/p>\n<pre>\u00a0\n&lt;?xml version=\"1.0\" ?&gt;\n&lt;root&gt;\n\u00a0 &lt;menu id=\"file\"\"\" value=\"File\"&gt;\n\u00a0\u00a0\u00a0 &lt;popup&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;menuitem&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;item value=\"New\" onclick=\"CreateNewDoc()\" \/&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;item value=\"Open\" onclick=\"OpenDoc()\" \/&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;item value=\"Close\" onclick=\"CloseDoc()\" \/&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0 &lt;\/menuitem&gt;\n\u00a0\u00a0\u00a0 &lt;\/popup&gt;\n\u00a0 &lt;\/menu&gt;\n&lt;\/root&gt;\n\u00a0\n\u00a0\n(1 row(s) affected)\n\u00a0\n\u00a0\n&lt;root&gt;&lt;menu id=\"file\"\"\" value=\"File\"&gt;&lt;popup&gt;&lt;menuitem&gt;&lt;item value=\"New\" onclick=\"CreateNewDoc()\" \/&gt;&lt;item value=\"Open\" onclick=\"OpenDoc()\" \/&gt;&lt;item value=\"Close\" onclick=\"CloseDoc()\" \/&gt;&lt;\/menuitem&gt;&lt;\/popup&gt;&lt;\/menu&gt;&lt;\/root&gt;\n\u00a0\n(1 row(s) affected)\n<\/pre>\n<h1>Wrap-up<\/h1>\n<p>The so-called &#8216;impedence-mismatch&#8217; between applications and databases is, I reckon, an illusion. The object-oriented nested data-structures that we receive from applications are, if the developer has understood the data correctly,\u00a0 merely a perspective from a particular entity of the relationships it is involved with. Whereas it is easy to shred XML documents to get the data from it to update the database, it has been trickier with other formats such as JSON. By using techniques like this, it should be possible to liberate the application, or website, programmer from having to do the mapping from the object model to the relational, and spraying the database with ad-hoc TSQL\u00a0 that uses the base tables or updateable views.\u00a0 If the database can be provided with the JSON, or the Table-Valued parameter, then there is a better chance of\u00a0 maintaining full transactional integrity for the more complex updates.<\/p>\n<p>The database developer already has the tools to do the work with XML, but why not the simpler, and more practical JSON? I hope these two routines get you started with experimenting with this.<\/p>\n<p><strong>Read also:<\/strong><br \/><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/techniques-to-query-azure-sqls-new-json-datatype\/\" target=\"_blank\" rel=\"noopener\">Azure SQL\u2019s native JSON data type techniques<\/a><br \/><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/techniques-to-query-azure-sqls-new-json-datatype\/\" target=\"_blank\" rel=\"noopener\">Subqueries in SQL SELECT statements<\/a><\/p>\n<h1>Interesting JSON-related articles and sites<\/h1>\n<ul>\n<li><a href=\"http:\/\/www.yaml.org\/\">YAML: YAML Ain&#8217;t Markup Language<\/a><\/li>\n<li><a href=\"http:\/\/en.wikipedia.org\/wiki\/XMLHttpRequest\">XMLHttpRequest<\/a><\/li>\n<li><a href=\"http:\/\/www.json.org\/\">Introducing JSON <\/a><\/li>\n<li><a href=\"http:\/\/www.json.org\/fatfree.html\">JSON: The Fat-Free Alternative to XML <\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/opinion\/geek-of-the-week\/doug-crockford-geek-of-the-week\/\">Doug Crockford: Geek of the Week<\/a><\/li>\n<li><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/json-and-other-data-serialization-languages\/\">JSON and other data serialization languages<\/a><\/li>\n<li><a href=\"http:\/\/en.wikipedia.org\/wiki\/WDDX\">WDDX <\/a><\/li>\n<li><a href=\"http:\/\/www.odata.org\/developers\/protocols\/json-format\">OData: JavaScript Object Notation (JSON) Format <\/a><\/li>\n<li><a href=\"http:\/\/bitworking.org\/projects\/atom\/rfc5023.html\">The Atom Publishing Protocol<\/a><\/li>\n<\/ul>\n<p class=\"note\">Since writing this article, Phil has also developed <a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/the-tsql-of-csv-comma-delimited-of-errors\/\"> a CSV parser and output<\/a> and an XML parser (<a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/t-sql-programming\/producing-json-documents-from-sql-server-queries-via-tsql\/\">Producing JSON Documents from SQL Server queries via TSQL<\/a>)<\/p>\n<\/div>\n\n\n<section id=\"my-first-block-block_958dd5b29d67cff32fd319c57d6065ee\" class=\"my-first-block alignwide\">\n    <div class=\"bg-brand-600 text-base-white py-5xl px-4xl rounded-sm bg-gradient-to-r from-brand-600 to-brand-500 red\">\n        <div class=\"gap-4xl items-start md:items-center flex flex-col md:flex-row justify-between\">\n            <div class=\"flex-1 col-span-10 lg:col-span-7\">\n                <h3 class=\"mt-0 font-display mb-2 text-display-sm\">Fast, reliable and consistent SQL Server development&#8230;<\/h3>\n                <div class=\"child:last-of-type:mb-0\">\n                                            &#8230;with SQL Toolbelt Essentials. 10 ingeniously simple tools for accelerating development, reducing risk, and standardizing workflows.                                    <\/div>\n            <\/div>\n                            <a href=\"https:\/\/www.red-gate.com\/products\/sql-toolbelt-essentials\/\" class=\"btn btn--secondary btn--lg\">Learn more &amp; try for free<\/a>\n                    <\/div>\n    <\/div>\n<\/section>\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs: Consuming JSON strings in SQL Server<\/h2>\n\n                        <h3 class=\"mt-4xl\">1. How do you parse JSON in SQL Server without OPENJSON?<\/h3>\n            <div class=\"faq-answer\">\n                <p>For SQL Server versions before 2016, or when you need custom parsing logic, you can build a T-SQL JSON parser using string manipulation functions. The approach converts JSON into an adjacency list (a hierarchical table where each row has a parent reference), which can then be queried relationally. This technique works on any SQL Server version and provides a table-valued function that shreds any valid JSON document into rows and columns.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">2. What is an adjacency list in the context of JSON and SQL Server?<\/h3>\n            <div class=\"faq-answer\">\n                <p>An adjacency list is a table structure where each row represents a node in a hierarchy, with columns for the node\u2019s ID, parent ID, name, and value. When applied to JSON, every property, array element, and nested object becomes a row linked to its parent via the parent ID. This representation allows standard SQL queries (JOINs, GROUP BY, WHERE) to navigate and extract data from any JSON structure, regardless of depth or complexity.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">3. Should you use built-in JSON functions or a custom parser in SQL Server?<\/h3>\n            <div class=\"faq-answer\">\n                <p>If you\u2019re on SQL Server 2016 or later, use the built-in functions (OPENJSON, JSON_VALUE, JSON_QUERY, FOR JSON) &#8211; they\u2019re optimized, maintained by Microsoft, and handle edge cases well. A custom parser is appropriate for pre-2016 instances, for learning purposes, or when you need parsing behavior the built-in functions don\u2019t support (e.g., custom validation or transformation during parsing).<\/p>\n            <\/div>\n            <\/section>\n","protected":false},"excerpt":{"rendered":"<p>Parse and consume JSON strings in SQL Server using T-SQL. Includes a custom JSON parser function, adjacency list techniques, and conversion between JSON and relational table formats.&hellip;<\/p>\n","protected":false},"author":154613,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143531],"tags":[4880,4357,4150,5134,4151,4183,4252,4217],"coauthors":[6813],"class_list":["post-1026","post","type-post","status-publish","format-standard","hentry","category-t-sql-programming-sql-server","tag-json","tag-phil-factor","tag-sql","tag-sql-prompt","tag-sql-server","tag-t-sql","tag-t-sql-programming","tag-xml"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1026","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/154613"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=1026"}],"version-history":[{"count":24,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1026\/revisions"}],"predecessor-version":[{"id":109060,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1026\/revisions\/109060"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=1026"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=1026"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=1026"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=1026"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}