JSON Parsing and Serialization in JavaScript
In JavaScript, handling JSON data is a very common operation, mainly involving two core methods:
1. JSON Parsing
The JSON.parse() method is used to convert a JSON string into a JavaScript object.
Basic Usage
javascriptconst jsonString = '{"name": "John", "age": 30, "city": "New York"}'; const obj = JSON.parse(jsonString); console.log(obj.name); // Output: John
Advanced Usage: Using reviver Function
JSON.parse() can accept a second parameter as a reviver function, used to transform the result during parsing:
javascriptconst jsonString = '{"name": "John", "birthDate": "2000-01-01"}'; const obj = JSON.parse(jsonString, (key, value) => { if (key === 'birthDate') { return new Date(value); } return value; }); console.log(obj.birthDate instanceof Date); // Output: true
2. JSON Serialization
The JSON.stringify() method is used to convert a JavaScript object into a JSON string.
Basic Usage
javascriptconst obj = {name: "John", age: 30, city: "New York"}; const jsonString = JSON.stringify(obj); console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}
Advanced Usage
2.1 Using replacer Parameter
You can specify which properties to include, or transform values:
javascriptconst obj = {name: "John", age: 30, city: "New York", salary: 50000}; // Include only specified properties const jsonString1 = JSON.stringify(obj, ['name', 'age']); // Transform values using function const jsonString2 = JSON.stringify(obj, (key, value) => { if (key === 'salary') { return value > 0 ? 'confidential' : value; } return value; });
2.2 Using space Parameter
Used to add indentation and whitespace, making the output more readable:
javascriptconst obj = {name: "John", age: 30, city: "New York"}; const jsonString = JSON.stringify(obj, null, 2); // Outputs formatted JSON string with 2-space indentation
Notes
- Circular References:If there are circular references in the object,
JSON.stringify()will throw an error. - undefined and Functions:These values are ignored (in objects) or converted to null (in arrays) during serialization.
- Date Objects:Will be converted to ISO-formatted strings.
- Regular Expressions:Will be converted to empty objects
{}. - Symbols:When used as object keys, they are ignored; when used as values, they are converted to undefined.