A generic code to convert your C# DataTable to JSON:
string makejsonoftable(DataTable table, makejson e)
{
StringBuilder sb = new StringBuilder();
foreach (DataRow dr in table.Rows)
{
if (sb.Length != 0)
sb.Append(",");
sb.Append("{");
StringBuilder sb2 = new StringBuilder();
foreach (DataColumn col in table.Columns)
{
string fieldname = col.ColumnName;
string fieldvalue = dr[fieldname].ToString();
if (sb2.Length != 0)
sb2.Append(",");
sb2.Append(string.Format("{0}:\"{1}\"", fieldname, fieldvalue));
}
sb.Append(sb2.ToString());
sb.Append("}");
}
if (e == makejson.e_with_square_brackets)
{
sb.Insert(0, "[");
sb.Append("]");
}
return sb.ToString();
}
and I added this enum:
enum makejson
{
e_without_square_brackets,
e_with_square_brackets
}
because you wont need the square brackets in case you are calling this function again for some nested object definition, for example like:
[{name:{name1:"ab",name2:"cd"},id:9}]
resulting json for one of my data query looked like this:
[{village_name:"Lourba leten",school_name:"EB 1.2 Nazare Gumer",village_id:"4030301",school_id:"525",classroom_id:"1893",location_name:"Seluk tan",location_id:"9"},{village_name:"",school_name:"",village_id:"",school_id:"",classroom_id:"1905",location_name:"Seluk tan",location_id:"9"}]
say you requested this through an ajax call, you can call a:
var jsondatastructure = eval (yourResponseText);
in case of the above sample result the "jsondatastructure" will have a jsondatastructure.length set to 2.