我正在使用这个函数来描述表。
填充数据表后使用
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 查询:“DESCRIBE 表名;”;DataTableToJSON(dataTable) 示例输出:
[
{"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":""}
]
用 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);