Home > Web Front-end > JS Tutorial > Introduction to object serialization in JavaScript_javascript skills

Introduction to object serialization in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:23:19
Original
1068 people have browsed it

Like the Java language, objects can be serialized and deserialized in JavaScript to save the object. In the ECMAScript 5 standard, object serialization in JavaScript is implemented through JSON.stringify(), while deserialization is implemented through JSON.parse():


Copy code The code is as follows:

var o = {x:1, y:29, z:42};
var s = JSON.stringify(o);
console.log(s);//{"x":1,"y":29,"z":42}
var c = JSON.parse(s);
console.log(c);//Object {x=1, y=29, z=42}


For browsers that only support the ECMAScript 3 standard, you can use json2.js written by Douglas Crockford (https://github.com/douglascrockford/JSON-js).

During the process of serializing the object, NaN, Infinity and -Infinity will be serialized into "null"; the Date object will be serialized into a string representing the corresponding time (but when deserialized using JSON.parse() , the time string will exist as an ordinary string and will not be reconstructed as a Date object).

When using JSON.stringify() to serialize an object, the serialized property is limited to the enumerable property of the object itself (Own). When JSON.stringify() is running, JavaScript will first check whether there is a toJSON() method in the object that needs to be serialized. If the toJSON() method exists, the method is called and the result returned is used as the target of serialization. If the toJSON() method does not exist, the default serialization method is used.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template