How to JSON.stringify and JSON.parse without getting an empty object?

the reason I am asking this question is because I want to use LocalStorage for my objects. And as you might know, when using LocalStorage you have to JSON.stringify the objects and then parse them back to javascript objects.

I am trying to JSON.stringify an object with methods and then parse it back but all I get is an empty object.

Please take a look at this code.

Person.js

function Person(name, telePhone) {

this.getName = function () {
    return name;
}

this.setName = function (_name) {
    name = _name;
}

this.getTelePhone = function () {
    return telePhone;
}

this.setTelePhone = function (_telePhone) {
    telepPhone = _telePhone;
}
};

Javascript.js

window.onload = function () {

var name = "John";
var telePhone = "073-2335662";

var personObject = new Person(name, telePhone);

console.log(personObject);
// returns: Person 
console.log(personObject.getName());
//returns: John

var test = JSON.stringify(personObject);
var newPersonObject = JSON.parse(test);

console.log(newPersonObject);
//returns: Object
console.log(newPersonObject.getName());
//returns: Uncaught TypeError: Object #<Object> has no method 'getName'
};

Any suggestions why this Person object after JSON.stringify and JSON.parse is empty and loses all it's methods?


Functions are not a valid JSON data type. And certainly the variable scope held by the functions can't be serialized.

You need to store data directly on the object to serialize it.

JSON has "object" (key/value pair) and "array" (ordered list) style structures, as well as string , number , true , false , and null .

http://json.org/


JSON.stringify would not serialize functions, because they are not data. JSON only stores real data and it's structure - variables, specifically. If you want to store functions as well, you can use .toString() method to convert a function source code to string, and to convert it back to function you can use eval() to create the method back, but this is a separate issue.

You will probably have to write your own serializer to perform this kind of task, the idea is pretty interesting, I will not be surprised if there is a ready solution for this.

链接地址: http://www.djcxy.com/p/40666.html

上一篇: JSON.parse和JSON.stringify不是幂等的,这是不好的

下一篇: 如何JSON.stringify和JSON.parse没有得到一个空的对象?