The JSON object of JavaScript itself has functions of serialization and deserialization, and for parse and stringify, we typically use these two functions to persist JSON objects.
Such as:
var persion = {
Username: "Kris",
Password: "1234567890"
}
Alert (Json.stringify (persion))//{"username": "Kris", "Password": "1234567890"}
The drawback is that stringify this function will convert all the properties, but sometimes we want to exclude some properties, such as the above password.
Hide some properties of an object with Tojson
This question and answer StackOverflow above provides a solution. That is, the replication Tojson method:
var Message = function () {
This.myprivateproperty = "Secret message";
This.mypublicproperty = "Message for the public";
This.tojson = function () {
return {
"Public": This.mypublicproperty
};
};
}
Alert (Json.stringify (New Message ())); {' Public ': ' Message for the Public '}
JSON detects the existence of the object's Tojson interface first when calling Stringify, and serializes it using the ToString of the object itself, if it exists. Replication Tojson can be applied not only on function-based objects, but also on object-based objects such as:
var persion = {
Name: ' Kris '
, password:1234567890
, Tojson:function () {return {name:this.name}}
};
Alert (Json.stringify (persion)); {"Name": "Kris"}
To define a hidden property on an object
The Tojson needs to implement an additional interface, and in ES5 there is a DefineProperty method that can be implemented by configuring parameters to define special properties, such as the ability to set this property to not enumerate:
var persion = {name: "Kris", Password: "1234567890"}
Setting properties
Object.defineproperty (persion, "password", {enumerable:false})
alert (Persion.password); 1234567890
Alert (Json.stringify (persion)); {"Name": "Kris"}
In fact, there are some more advanced properties of defineproperty, such as adding Get/set method for attributes, but because of incompatible with the old version of IE, so there is not much on the front end, more used in the backend node. js.
Two ways to exclude certain properties when JSON serialization (Stringify) objects