javascriptは対象をJsonに変換します.
2355 ワード
<SPAN style="FONT-SIZE: small">var userName;
var age;
// Person
var Person = function(userName, age) {
this.userName = userName;
this.age = age;
}
//
var personArrays = new Array();
var p1 = new Person("DT", 22);
var p2 = new Person("Jacky", 26);
var p3 = new Person("Lily", 21);
personArrays.push(p1);
personArrays.push(p2);
personArrays.push(p3);
// array Json
function f_evalArray(obj) {
var arrays = obj;
for (var i = 0;i < arrays.length; i++) {
if (typeof arrays[i] == "object") {
arrays[i] = obj2str(arrays[i]);
}
}
return "[" + arrays + "]";
}
// json
function obj2str(o) {
var r = [];
if (typeof o == "string")
return "\""
+ o.replace(/([\'\"\\])/g, "\\$1").replace(/(
)/g, "\
")
.replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
if (typeof o == "object") {
if (!o.sort) {
for (var i in o)
r.push(i + ":" + obj2str(o[i]));
if (!!document.all
&& !/^
?function\s*toString\(\)\s*\{
?\s*\[native code\]
?\s*\}
?\s*$/
.test(o.toString)) {
r.push("toString:" + o.toString.toString());
}
r = "{" + r.join() + "}"
} else {
for (var i = 0;i < o.length; i++)
r.push(obj2str(o[i]))
r = "[" + r.join() + "]"
}
return r;
}
return o.toString();
}
// JSON
var OString = function(O) {
var S = [];
for (var i in O) {
O[i] = typeof O[i] == "string" ? O[i] : (typeof O[i] == "object"
? OString(O[i])
: O[i]);
S.push("'" + i + "':'" + O[i] + "'");
}
return '{' + S.join(',') + '}';
}
console.info(f_evalArray(personArrays));