Introduction to Object serialization in JavaScript _javascript tips

Source: Internet
Author: User
Tags object serialization serialization tojson

As with the Java language, you can save objects by serializing and deserializing them in JavaScript. In the ECMAScript 5 standard, Object serialization in JavaScript is accomplished by Json.stringify (), while deserialization is achieved by Json.parse ():


Copy Code code as follows:

var o = {x:1, y:29, z:42};
var s = json.stringify (o);
Console.log (s);//{"x": 1, "Y": S, "Z": 42}
var C = json.parse (s);
Console.log (c);//object {x=1, y=29, z=42}


For browsers that support only the ECMAScript 3 standard, you can use the Json2.js (HTTPS://GITHUB.COM/DOUGLASCROCKFORD/JSON-JS) written by Douglas Crockford.

During serialization of objects, NaN, infinity, and-infinity are serialized as "null"; The date object will be serialized as a string representing the corresponding time (but when deserialized using Json.parse (), the time string will exist as a normal string. Will not be rebuilt as a Date object).

When you serialize an object using Json.stringify (), the serialized property is limited to the enumerable property of the object itself (OWN). While Json.stringify () is running, JavaScript first looks for the Tojson () method in the object that needs to be serialized, and if the Tojson () method exists, calls the method and returns the result as the target of the serialization. If the Tojson () method does not exist, the default serialization method is used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.