How to useJSON.stringify() and JSON.parse() in Javascript
Using JSON.stringify() converts an object to a JSON string. this is how serialization occurs. JSON.parse() then restores the object from the string. It’s simple but doesn’t directly handle class types.
Syntax:
JSON.stringify(value, replacer, space);
JSON.parse( string, function );
Example: We Serialize and restore the Person class instance result. Serializes with JSON.stringify() and restores with JSON.parse(), ensuring proper class type restoration.
Javascript
class Person { constructor(name, age) { this .name = name; this .age = age; } } const result = new Person( 'Rahul' , 15); const serializedResult = JSON.stringify(result); const deserializedResult = JSON.parse(serializedResult, (key, value) => key === '' && value && value.__class === 'Person' ? new Person(value.name, value.age) : value ); console.log(deserializedResult); |
{ name: 'Rahul', age: 15 }
How to Dynamically Serialise & Restore ES6 Class Types in JavaScript ?
Dynamically serializing and restoring ES6 class types in JavaScript refers to the process of converting instances of ES6 classes into a format (e.g., JSON) that can be stored or transmitted, and then reconstructing those instances from the serialized data, preserving their class structure and behavior.
These are the following ways:
Table of Content
- Using JSON.stringify() and JSON.parse()
- Using Object.assign() and Object.setPrototypeOf():