title: DataTable to JSON
body: <p>I recently needed to serialize a datatable to JSON.  Where I'm at we're still on .Net 2.0, so I can't use the JSON serializer in .Net 3.5.  I figured this must have been done before, so I went looking online and <a href="http://www.codeproject.com/KB/aspnet/ASPNET_DataTable_to_JSON.aspx" rel="nofollow noreferrer">found</a> a <a href="http://www.dennydotnet.com/post/A-DataTable-Serializer-for-ASPNET-AJAX.aspx" rel="nofollow noreferrer">number</a> of <a href="http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/" rel="nofollow noreferrer">different</a> <a href="https://web.archive.org/web/20200204000610/http://geekswithblogs.net/shahed/archive/2008/03/22/120709.aspx" rel="nofollow noreferrer">options</a>.  Some of them depend on an additional library, which I would have a hard time pushing through here.  Others require first converting to <code>List&lt;Dictionary&lt;&gt;&gt;</code>, which seemed a little awkward and needless.  Another treated all values like a string.  For one reason or another I couldn't really get behind any of them, so I decided to roll my own, which is posted below.</p>
  <p>As you can see from reading the <code>//TODO</code> comments, it's incomplete in a few places.  This code is already in production here, so it does &quot;work&quot; in the basic sense.  The places where it's incomplete are places where we know our production data won't currently hit it (no timespans or byte arrays in the db).  The reason I'm posting here is that I feel like this can be a little better, and I'd like help finishing and improving this code.  Any input welcome.</p>
  <p><em>Note that this capability is built into .Net 3.5 and later, and so the only reason to use this code today is if you're still limited to .Net 2.0. Even then, JSON.Net has become the goto library for this kind of thing.</em></p>
  <pre><code>public static class JSONHelper
  {
      public static string FromDataTable(DataTable dt)
      {
          string rowDelimiter = &quot;&quot;;
  
          StringBuilder result = new StringBuilder(&quot;[&quot;);
          foreach (DataRow row in dt.Rows)
          {
              result.Append(rowDelimiter);
              result.Append(FromDataRow(row));
              rowDelimiter = &quot;,&quot;;
          }
          result.Append(&quot;]&quot;);
  
          return result.ToString();
      }
  
      public static string FromDataRow(DataRow row)
      {
          DataColumnCollection cols = row.Table.Columns;
          string colDelimiter = &quot;&quot;;
  
          StringBuilder result = new StringBuilder(&quot;{&quot;);       
          for (int i = 0; i &lt; cols.Count; i++)
          { // use index rather than foreach, so we can use the index for both the row and cols collection
              result.Append(colDelimiter).Append(&quot;\&quot;&quot;)
                    .Append(cols[i].ColumnName).Append(&quot;\&quot;:&quot;)
                    .Append(JSONValueFromDataRowObject(row[i], cols[i].DataType));
  
              colDelimiter = &quot;,&quot;;
          }
          result.Append(&quot;}&quot;);
          return result.ToString();
      }
  
      // possible types:
      // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx
      private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double), 
                                       typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single),
                                       typeof(UInt16), typeof(UInt32), typeof(UInt64)};
  
      // I don't want to rebuild this value for every date cell in the table
      private static long EpochTicks = new DateTime(1970, 1, 1).Ticks;
  
      private static string JSONValueFromDataRowObject(object value, Type DataType)
      {
          // null
          if (value == DBNull.Value) return &quot;null&quot;;
  
          // numeric
          if (Array.IndexOf(numeric, DataType) &gt; -1)
              return value.ToString(); // TODO: eventually want to use a stricter format. Specifically: separate integral types from floating types and use the &quot;R&quot; (round-trip) format specifier
  
          // boolean
          if (DataType == typeof(bool))
              return ((bool)value) ? &quot;true&quot; : &quot;false&quot;;
  
          // date -- see https://weblogs.asp.net/bleroy/dates-and-json
          if (DataType == typeof(DateTime))       
              return &quot;\&quot;\\/Date(&quot; + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + &quot;)\\/\&quot;&quot;;
  
          // TODO: add Timespan support
          // TODO: add Byte[] support
  
          //TODO: this would be _much_ faster with a state machine
          //TODO: way to select between double or single quote literal encoding
          //TODO: account for database strings that may have single \r or \n line breaks
          // string/char  
          return &quot;\&quot;&quot; + value.ToString().Replace(@&quot;\&quot;, @&quot;\\&quot;).Replace(Environment.NewLine, @&quot;\n&quot;).Replace(&quot;\&quot;&quot;, @&quot;\&quot;&quot;&quot;) + &quot;\&quot;&quot;;
      }
  }
  </code></pre>
  <p><strong>Update:</strong><br />
  This is old now, but I wanted to point out something about how this code handles dates. The format I used made sense at the time, for the exact rationale in the commented url. However, that rationale includes the following:</p>
  <blockquote>
  <p>To be perfectly honest, JSON Schema does solve the problem by making it possible to &quot;subtype&quot; a string as a date literal, but this is still work in progress and it will take time before any significant adoption is reached.</p>
  </blockquote>
  <p>Well, time has passed. Today, it's okay to just use the <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer">ISO 8601</a> date format. I'm not gonna bother changing the code, 'cause really: this is ancient. Just go use JSON.Net.</p>