使用JavaScript序列化任意复杂的对象
在phonegap的开发中,有时需要知道对象的所有属性,就简单的写了个序列化的方法。
序列化方法如下:
1 function serialize(obj, name) { 2 var result = ""; 3 function serializeInternal(o, path) { 4 for (p in o) { 5 var value = o[p]; 6 if (typeof value != "object") { 7 result += "\n" + path + "." + p + " = " + value; 8 } 9 else { 10 if (p * 1 >= 0) { 11 serializeInternal(value, path + '[' + p + ']'); 12 } else { 13 serializeInternal(value, path + '.' + p); 14 } 15 } 16 } 17 } 18 19 serializeInternal(obj, name); 20 return result; 21 }
测试一下:
1 var contacts = [ 2 { 3 displayName: "Mike", 4 phoneNumbers: [ 5 { 6 type: "string", 7 value: "0722829323123", 8 pref: false 9 } 10 ] 11 }, 12 { 13 displayName: "Leo", 14 phoneNumbers: [ 15 { 16 type: "string", 17 value: "03837234343", 18 pref: false 19 }, 20 { 21 type: "string", 22 value: "005543834", 23 pref: true 24 } 25 ] 26 } 27 ]; 28 29 alert(serialize(contacts, "contacts"));
运行结果: