// 序列化一张表
var MySerialize = function (obj) {
//return JSON.stringify(obj, null, 4);
{ // 写完这个函数才发现 JSON.stringify(obj, null, 4) 就能转,蛋疼
if (typeof(obj) != "object" || obj == null)
{
return String(obj);
}
var outStr = "";
var outStrList = [];
var iCount = 0;
var Serialize = function (o, spaceStr) {
var dSpaceStr = "\t";
spaceStr = spaceStr || "";
if (typeof(o) == "string")
{
outStrList[iCount] = "\"";
iCount++;
outStrList[iCount] = String(o);
iCount++;
outStrList[iCount] = "\"";
iCount++;
}
else if (typeof(o) != "object" || o == null) {
outStrList[iCount] = String(o);
iCount++;
}
else { // object
if (o.constructor == Array) {
var has = false;
outStrList[iCount] = "[\n";
iCount++;
for (var i = 0; i < o.length; i++) {
has = true;
var v = o[i];
outStrList[iCount] = spaceStr;
iCount++;
outStrList[iCount] = dSpaceStr;
iCount++;
Serialize(v, spaceStr + dSpaceStr);
outStrList[iCount] = ",\n";
iCount++;
}
if (has) {
iCount--;
outStrList[iCount] = "\n";
iCount++;
}
outStrList[iCount] = spaceStr;
iCount++;
outStrList[iCount] = "]";
iCount++;
}
else { // table
var has = false;
outStrList[iCount] = "{\n";
iCount++;
for (var k in o) {
has = true;
var v = o[k];
outStrList[iCount] = spaceStr;
iCount++;
outStrList[iCount] = dSpaceStr;
iCount++;
outStrList[iCount] = "\"";
iCount++;
outStrList[iCount] = k;
iCount++;
outStrList[iCount] = "\": ";
iCount++;
Serialize(v, spaceStr + dSpaceStr);
outStrList[iCount] = ",\n";
iCount++;
}
if (has) {
iCount--;
outStrList[iCount] = "\n";
iCount++;
}
outStrList[iCount] = spaceStr;
iCount++;
outStrList[iCount] = "}";
iCount++;
}
}
}
Serialize(obj);
outStr = outStrList.join("");
return outStr;
}
}
var table = {a: 1, b: 2, c: 3, d: function() {return 0}};
console.log("table: " + JSON.stringify(table, null, 4));
console.log("table: " + MySerialize(table));
输出为
table: {
"a": 1,
"b": 2,
"c": 3
}
table: {
"a": 1,
"b": 2,
"c": 3,
"d": function () {return 0}
}