DataTable
. DataTable
into a JSON object.
I am using this function for describe table.
Use it after fill datatable
static public string DataTableToJSON(DataTable dataTable,bool readableformat=true)
{
string JSONString="[";
string JSONRow;
string colVal;
foreach(DataRow dataRow in dataTable.Rows)
{
if(JSONString!="[") { JSONString += ","; }
JSONRow = "";
if (readableformat) { JSONRow += "\r\n"; }
JSONRow += "{";
foreach (DataColumn col in dataTable.Columns)
{
colVal = dataRow[col].ToString();
colVal = colVal.Replace("\"", "\\\"");
colVal = colVal.Replace("'", "\\\'");
if(JSONRow!="{"&&JSONRow!="\r\n{") {
JSONRow += ",";
}
JSONRow += "\"" + col.ColumnName + "\":\"" + colVal + "\"";
}
JSONRow += "}";
JSONString += JSONRow;
}
JSONString += "\r\n]";
return JSONString;
}
MySQL Query: "DESCRIBE TableName;"; DataTableToJSON(dataTable) Example Output:
[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]
Tested With PHP:
$X='[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]';
$Y=json_decode($X,true);
echo $Y[0]["Field"];
var_dump($Y);