JSON.parse() and JSON.stringify() usage

The JSON.parse() method is used to convert a JSON-formatted string to a JavaScript object, and the JSON.stringify() method is used to convert a JavaScript object to a JSON string. These two methods can be used in combination to convert data from objects to strings to objects.

example

// 创建一个包含属性的 JavaScript 对象
var person = {
    
    
  name: "Alice",
  age: 25,
  city: "New York"
};

// 将 JavaScript 对象转换为 JSON 字符串
var jsonString = JSON.stringify(person);
console.log(jsonString); // 输出:{"name":"Alice","age":25,"city":"New York"}

// 将 JSON 字符串转换为 JavaScript 对象
var parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // 输出:Alice
console.log(parsedData.age);  // 输出:25
console.log(parsedData.city); // 输出:New York

Guess you like

Origin blog.csdn.net/m0_47791238/article/details/132265756