Click here to Skip to main content
Click here to Skip to main content

Convert ASP.NET DataTable to JSON, to use a DataTable in JavaScript

By , 28 Jun 2007
 

Introduction

Web development is changing day by day, and it has been changing from day one. Nowadays, every developer has his/her own writing style. Some like pure, server side, and some like a mixture. Nowadays JavaScript is just like a boom in the market. And the way MS (Microsoft) has implemented it is a great job.

But there are still many things we do on our own. Here I am going to demonstrate an example by which we can convert an ASP.NET DataTable in to a JSON string in two ways. It will be very useful to use it in JavaScript.

This will solve the problem for developers on how to use server data on the client side in a well structured manner.

Background

It is assumed that the person who will use this has a good knowledge of JSON and how to manipulate it in the server.

Code

public string JSON_DataTable(DataTable dt)
{

    /****************************************************************************
    * Without goingin to the depth of the functioning
    * of this method, i will try to give an overview
    * As soon as this method gets a DataTable
    * it starts to convert it into JSON String,
    * it takes each row and ineach row it creates
    * an array of cells and in each cell is having its data
    * on the client side it is very usefull for direct binding of object to  TABLE.
    * Values Can be Access on clien in this way. OBJ.TABLE[0].ROW[0].CELL[0].DATA 
    * NOTE: One negative point. by this method user
    * will not be able to call any cell by its name.
    * *************************************************************************/

    StringBuilder JsonString = new StringBuilder();

    JsonString.Append("{ ");
    JsonString.Append("\"TABLE\":[{ ");
    JsonString.Append("\"ROW\":[ ");

    for (int i = 0; i < dt.Rows.Count; i++)
    {

        JsonString.Append("{ ");
        JsonString.Append("\"COL\":[ ");

        for (int j = 0; j < dt.Columns.Count; j++)
        {
            if (j < dt.Columns.Count - 1)
            {
                JsonString.Append("{" + "\"DATA\":\"" + 
                                  dt.Rows[i][j].ToString() + "\"},");
            }
            else if (j == dt.Columns.Count - 1)
            {
                JsonString.Append("{" + "\"DATA\":\"" + 
                                  dt.Rows[i][j].ToString() + "\"}");
            }
        }
        /*end Of String*/
        if (i == dt.Rows.Count - 1)
        {
            JsonString.Append("]} ");
        }
        else
        {
            JsonString.Append("]}, ");
        }
    }
    JsonString.Append("]}]}");
    return JsonString.ToString();
}

//b)
public string CreateJsonParameters(DataTable dt)
{
    /* /****************************************************************************
     * Without goingin to the depth of the functioning
     * of this method, i will try to give an overview
     * As soon as this method gets a DataTable it starts to convert it into JSON String,
     * it takes each row and in each row it grabs the cell name and its data.
     * This kind of JSON is very usefull when developer have to have Column name of the .
     * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
     * NOTE: One negative point. by this method user
     * will not be able to call any cell by its index.
     * *************************************************************************/

     StringBuilder JsonString = new StringBuilder();

    //Exception Handling
    if (dt != null && dt.Rows.Count > 0)
    {
        JsonString.Append("{ ");
        JsonString.Append("\"Head\":[ ");

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            JsonString.Append("{ ");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (j < dt.Columns.Count - 1)
                {
                    JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + 
                          "\":" + "\"" + 
                          dt.Rows[i][j].ToString() + "\",");
                }
                else if (j == dt.Columns.Count - 1)
                {
                    JsonString.Append("\"" + 
                       dt.Columns[j].ColumnName.ToString() + "\":" + 
                       "\"" + dt.Rows[i][j].ToString() + "\"");
                }
            }

            /*end Of String*/
            if (i == dt.Rows.Count - 1)
            {
                JsonString.Append("} ");
            }
            else
            {
                JsonString.Append("}, ");
            }
        }

        JsonString.Append("]}");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}

Using the Code

As you can see, the code is very easy to understand. These functions are ready to use. You can find the full source code in the download source code section.

Using the JSON_DataTable method

  1. Add the namespace:
  2. using Ravs.Factory.JSON;
  3. Create the object:
  4. JSON_Class Object_JSON_Class = new JSON_Class();
  5. Use of first case JSON:
  6. Object_JSON_Class.JSON_DataTable(ProvideRequiredDataTable);

    Here, the above method will provide a JSON stirng which you can use on the client.

  7. Now put this data in someplace where it is very easy to render to the client for further use. I'll show how to put it in to a text field (the most easy one.)
  8. Put a server text box on to your form. And do this:

    ServerSideTextBox.Text= Object_JSON_Class. JSON_DataTable(ProvideRequiredDataTable);
  9. On the client end.. use JavaScript like this:
  10. <script type='text/javascript'> 
    var oServerSideTextBox= document.getElementbyId("ServerSideTextBox"); 
    var oServerJSON_String=eval("("+oServerSideTextBox .value+")"); 
    alert(oServerJSON.TABLE[0].ROW[0].COL[0].DATA); 
    // if alert comes with right Data then, CHEERS J 
    </script>

Using the CreateJsonParameters method

  1. Add the namespace:
  2. using Ravs.Factory.JSON; 
  3. Create the object:
  4. JSON_Class Object_JSON_Class = new JSON_Class(); 
  5. Use of first case JSON:
  6. Object_JSON_Class.CreateJsonParameters (ProvideRequiredDataTable);

    Here, the above method will provide a JSON string which you can use on the client.

  7. Now put this data in someplace where it is very easy to render to the client for further use.. I'll show how to put it in to a text field (the most easy one):
  8. Put a server text box on to your form. And do this.

    ServerSideTextBox.Text= 
      Object_JSON_Class.CreateJsonParameters (ProvideRequiredDataTable);
  9. On the client end.. use JavaScript like this:
  10. <script type='text/javascript'> 
    var oServerSideTextBox= document.getElementbyId("ServerSideTextBox"); 
    var oServerJSON_String=eval("("+oServerSideTextBox .value+")"); 
    alert(oServerJSON.HEAD[0].AnyColumnName); 
    // if alert comes with right Data then, CHEERS J 
    </script>

Note: To know more, check out the source and demo projects.

Cheers :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

blue_arc
Software Developer (Senior) Connexxions Business Support Services
India India
Member
Social Group (No members)

My Name is Ravi Kant Srivastava. Alias= ravs
 
DOTNET Consultant
Mumbai

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI am using this with AJAX to send back JSON formatted resultsmembertjvaliant12321 Mar '12 - 8:22 
I am using this with AJAX to send back JSON formatted results. So the JSON produced is my xmlhttp.responseText. I am having an issue converting this to a JSON object in javascript. I have tried using eval and JSON.parse, but no luck.
 
Let me know if you have any ideas.
 
Thanks,
Todd
GeneralMy vote of 5membermanoj kumar choubey16 Feb '12 - 1:23 
Nice
GeneralMy vote of 4memberJeffrey Schaefer25 Nov '11 - 21:50 
Nice and simple. Would have voted 5 if you took the time to move the important revision suggested by Alexandru Matei to the article text as a new revision. Nice work, anyway.
GeneralMy vote of 5memberolavolsf19 Jan '11 - 18:31 
code runs without problem. It is very efficient and allows us to easily cache tables at clientside.
GeneralMy vote of 5memberfgutierrez8616 Dec '10 - 3:36 
Just converted to vb, press run.
Up and running...
Thanks!!...
GeneralSuggestions [modified]memberAlexandru Matei11 Sep '07 - 9:19 
Hello,
 
I would suggest the following improvements:
 
1. Add support for the following C# data types:
- boolean variables (true/false)
- numbers (integers, decimal, floating point)
- System.DateTime
 
2. Add support for the following special characters:
- ' (apostrophe)
- " (quote)
- \r\n (new line)
- \ (backslash)
 

In your JSON_DataTable() function, instead of writing:
JsonString.Append("{" + "\"DATA\":\"" + dt.Rows[i][j].ToString() + "\"}");
you could have written something like this:
 
public string JSON_DataTable(DataTable dt)
        {
            
            StringBuilder JsonString = new StringBuilder();
            JsonString.Append("{ ");
            JsonString.Append("\"TABLE\":[{ ");
            JsonString.Append("\"ROW\":[ ");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
 
                JsonString.Append("{ ");
                JsonString.Append("\"COL\":[ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                     
 
                       switch (dt.Columns[j].DataType.ToString())
                        {
                            case "System.DateTime":
                               JsonString.Append("{ \"DATA\": " );
                               DateTime cv = (DateTime)dt.Rows[i][j];
                                //The Date JavaScript class uses 0-based indexes for months
                                JsonString.Append("new Date(" + cv.Year + "," + (cv.Month - 1) + "," + cv.Day + "," + cv.Hour + "," + cv.Minute + "," + cv.Second + "," + cv.Millisecond + ")");
                                JsonString.Append("} ");
                                 break;
 
                            case "System.Boolean":
                               JsonString.Append("{ \"DATA\": " );
                               JsonString.Append(dt.Rows[i][j].ToString().ToLower());
                                JsonString.Append("}");
                                break;
                            case "System.Decimal":
                            case "System.Single":
                            case "System.Double":
                            case "System.UInt16":
                            case "System.UInt32":
                            case "System.Int16":
                            case "System.Int32":
                            case "System.Byte":
                            case "System.SByte":
 
                                  JsonString.Append("{ \"DATA\": " );
                                  JsonString.Append(dt.Rows[i][j].ToString() );
                                JsonString.Append("}");
                                break;
 
                            default:
                                
                                JsonString.Append("{ \"DATA\":\""); 
 
                                StringBuilder columnValue = new StringBuilder();
                                columnValue.Append(dt.Rows[i][j].ToString() );
                               
 
                                //    replace single backslash with double backslash (e.g. (e.g. TOM\\ASPNET -> TOM\\\\ASPNET)
                                columnValue = columnValue.Replace("\\", "\\\\\\\\");
 
                                //replace  \" with \\\\\"  (double quotes)
                                columnValue = columnValue.Replace("\" ", "\\\\\"");
 
                                //replace  '  with \'  ( apostrophe characters)
                                columnValue = columnValue.Replace("'", "\\\'");
 
                                //replace simple \r with \\r
                                columnValue = columnValue.Replace("\r", "\\\\r");
 
                                //replace simple \n with \\n
                                columnValue = columnValue.Replace("\n", "\\\\n");
 
                                JsonString.Append(columnValue);
 
                                JsonString.Append("\"}");
                               
                                break;
                        }
   
                    
                   
 
                    if (j < dt.Columns.Count - 1)
                    {
                        JsonString.Append(",");
                    }
                    
 
                }
                /*end Of String*/
                if (i == dt.Rows.Count - 1)
                {
                    JsonString.Append("]} ");
                }
                else
                {
                    JsonString.Append("]}, ");
                }
            }
            JsonString.Append("]}]}");
            return JsonString.ToString();
        }
 
The generated JSON strings will look something like this:
 
var a='{ "TABLE":[{ "ROW":[ { "COL":[ { "DATA":"Sibiu"},{ "DATA":"Romania"}]}, { "COL":[ { "DATA":"Chester \' \\\\ field"},{ "DATA":"United \\r\\n Kingdom \\""}]} ]}]}';
 

var t='{ "TABLE":[{ "ROW":[ { "COL":[ { "DATA":"TOMSMI"},{ "DATA":"Tom Smith"},{ "DATA":"DAT001"},{ "DATA": true},{ "DATA": 30},{ "DATA": new Date(1968,9,9,8,15,0,420)} ,{ "DATA": 25},{ "DATA": 1.1},{ "DATA": 3.3},{ "DATA": 245},{ "DATA":"a"}]}, { "COL":[ { "DATA":"ANTANU"},{ "DATA":"Anton Anuta"},{ "DATA":"INS001"},{ "DATA": true},{ "DATA": 120},{ "DATA": new Date(2007,8,11,22,6,19,625)} ,{ "DATA": 25},{ "DATA": 1.1},{ "DATA": 3.3},{ "DATA": 245},{ "DATA":"a"}]} ]}]}';
And the evaluation goes on something like this:
 
var addresses = eval("("+ a +")") ; 
alert(addresses.TABLE[0].ROW[0].COL[0].DATA+' - '+addresses.TABLE[0].ROW[0].COL[1].DATA);
alert(addresses.TABLE[0].ROW[1].COL[0].DATA+' - '+addresses.TABLE[0].ROW[1].COL[1].DATA);
     
var testers = eval("("+ t +")") ; 
alert(testers.TABLE[0].ROW[0].COL[3].DATA+' - '+testers.TABLE[0].ROW[0].COL[4].DATA);
 
alert(testers.TABLE[0].ROW[0].COL[4].DATA+' - '+testers.TABLE[0].ROW[0].COL[5].DATA);
 

 

 

 
-- modified at 15:45 Tuesday 11th September, 2007
AnswerRe: Suggestionsmemberblue_arc11 Sep '07 - 21:02 
hello Alexandru,
 
Thanks buddy.....
actuall i had a requirment in past to do something like this...... so I did.. and moved on...
and never got time for this... but you have suggested a good thing.... I will look forward to it....
neways Thanks and keep it up Smile | :)
 
Ravi Kant Srivastava
(System Analyst)
HandsOn Technology & Engineering
Gurgaon
(India)
e-mail:ravikant@hte.co.in

GeneralRe: SuggestionsmemberAndrew Timmins5 Nov '07 - 10:25 
SWEET!
I was just about to code all the replace code in. I went to the bottom of the page to provide a comment.
But its already done for me.
Nice work guys!
 

GeneralAppendFormatmvpMark Nischalke29 Jun '07 - 2:09 
IMO using AppendFormat rather than Append would make teh code cleaner and more readable
 

only two letters away from being an asset

GeneralRe: AppendFormatmemberKansasCoder31 Dec '09 - 9:20 
Appendformat is cleaner but it is significantly slower than append. imo the upperhand should always go to performance on the network rather than ease of maintenance or legibility.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 29 Jun 2007
Article Copyright 2007 by blue_arc
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid