乐闻世界logo
搜索文章和话题

How to parse and serialize JSON data in JavaScript?

2月25日 23:17

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

javascript
const 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:

javascript
const 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

javascript
const 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:

javascript
const 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:

javascript
const obj = {name: "John", age: 30, city: "New York"}; const jsonString = JSON.stringify(obj, null, 2); // Outputs formatted JSON string with 2-space indentation

Notes

  1. Circular References:If there are circular references in the object, JSON.stringify() will throw an error.
  2. undefined and Functions:These values are ignored (in objects) or converted to null (in arrays) during serialization.
  3. Date Objects:Will be converted to ISO-formatted strings.
  4. Regular Expressions:Will be converted to empty objects {}.
  5. Symbols:When used as object keys, they are ignored; when used as values, they are converted to undefined.
标签:JSON