Поднимем тему Мне тут вдруг понадобилось кое-чево сериализовать. Скачал этот скрипт но почему-то под Windows Script Host он не заработал. Да и не очень хотелось Своё всегда интереснее писать. Написал. Весьма небольшая в вместе с тем универсальная функция. Привожу вместе с примером
CODE:
function serialize(value)
{
var NL = "\r\n", TAB = "\t", out = new Array(), facttype;
if (value instanceof Array) facttype = "array";
else if (value instanceof RegExp) facttype = "regexp";
else if (value instanceof Function) facttype = "function";
else if (value instanceof Object) facttype = "object";
else facttype = typeof(value);
switch(facttype)
{
case "object":
for (var i in value)
out.push(serialize(i) + ": " + serialize(value[i]));
return "{"+(NL+out.join(","+NL)).replace(/\n/g,"\n"+TAB)+NL+"}";
case "array":
for (var i=0;i<value.length;i++)
out.push(serialize(value[i]));
return "["+(NL+out.join(","+NL)).replace(/\n/g,"\n"+TAB)+NL+"]";
case "string":
var r1 = [/\t/g, /\r/g, /\n/g, /"/g, /\\/g ];
var r2 = ["\\t", "\\r", "\\n", "\\\"","\\\\"];
while (r1.length) value = value.replace(r1.pop(),r2.pop());
return '"' + value +'"';
default:
return value.toString().replace(/\n/g,"\n"+TAB);
}
}
var test = {
adin: false,
dva: [3,2,1,6,7],
tri: {imya: "vasia", familiya: "pupkin"},
chetire: /(.+)/,
piat: function (d) { return d/2; },
bIbIbI: "\\djt \"yj\" yjy \
gh\n_ drt j\n\
"
};
eval("var clon="+serialize(test));
WScript.echo("test = " + serialize(test) + ";\n\
//===========================\n\
clon = " + serialize(clon) + ";");
{
var NL = "\r\n", TAB = "\t", out = new Array(), facttype;
if (value instanceof Array) facttype = "array";
else if (value instanceof RegExp) facttype = "regexp";
else if (value instanceof Function) facttype = "function";
else if (value instanceof Object) facttype = "object";
else facttype = typeof(value);
switch(facttype)
{
case "object":
for (var i in value)
out.push(serialize(i) + ": " + serialize(value[i]));
return "{"+(NL+out.join(","+NL)).replace(/\n/g,"\n"+TAB)+NL+"}";
case "array":
for (var i=0;i<value.length;i++)
out.push(serialize(value[i]));
return "["+(NL+out.join(","+NL)).replace(/\n/g,"\n"+TAB)+NL+"]";
case "string":
var r1 = [/\t/g, /\r/g, /\n/g, /"/g, /\\/g ];
var r2 = ["\\t", "\\r", "\\n", "\\\"","\\\\"];
while (r1.length) value = value.replace(r1.pop(),r2.pop());
return '"' + value +'"';
default:
return value.toString().replace(/\n/g,"\n"+TAB);
}
}
var test = {
adin: false,
dva: [3,2,1,6,7],
tri: {imya: "vasia", familiya: "pupkin"},
chetire: /(.+)/,
piat: function (d) { return d/2; },
bIbIbI: "\\djt \"yj\" yjy \
gh\n_ drt j\n\
"
};
eval("var clon="+serialize(test));
WScript.echo("test = " + serialize(test) + ";\n\
//===========================\n\
clon = " + serialize(clon) + ";");