JSON

js/json2026-08-24 19:46:25

JavaScript 中的 JSON 对象提供了用于解析和序列化 JSON 数据的静态方法。

解析 JSON 字符串

JSON.parse(text, reviver) 将 JSON 字符串解析为 JavaScript 对象。

// JSON 字符串
const jsonString = '{"name": "Alice", "age": 25, "city": "Wonderland"}';

// 使用 JSON.parse 将 JSON 字符串解析为 JavaScript 对象
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject); // 输出: { name: 'Alice', age: 25, city: 'Wonderland' }

可选的 reviver 参数是一个函数,用于在解析过程中对每个属性进行转换。

// 使用 reviver 参数转换属性值
const parsedObjectWithReviver = JSON.parse(jsonString, (key, value) => {
  if (key === 'age') {
    return value + 1; // 将 age 属性值加 1
  }
  return value;
});
console.log(parsedObjectWithReviver); // 输出: { name: 'Alice', age: 26, city: 'Wonderland' }

序列化 JSON 数据

JSON.stringify(value, replacer, space) 将 JavaScript 对象序列化为 JSON 字符串。

// 使用 JSON.stringify 将 JavaScript 对象序列化为 JSON 字符串
const newJsonString = JSON.stringify(jsonObject);
console.log(newJsonString); // 输出: {"name":"Alice","age":25,"city":"Wonderland"}

可选的 replacer 参数可以是一个函数或数组,用于指定哪些属性应该被序列化。

// 使用 replacer 参数过滤属性
const filteredJsonString = JSON.stringify(jsonObject, ['name', 'city']);
console.log(filteredJsonString); // 输出: {"name":"Alice","city":"Wonderland"}

可选的 space 参数用于控制输出的缩进。

// 使用 space 参数格式化输出
const formattedJsonString = JSON.stringify(jsonObject, null, 2);
console.log(formattedJsonString);
/*
输出:
{
  "name": "Alice",
  "age": 25,
  "city": "Wonderland"
}
*/

注意事项

  • JSON.parse 和 JSON.stringify 只能处理有效的 JSON 数据。无效的 JSON 数据会导致解析错误。
  • JSON 数据格式要求属性名称必须用双引号括起来,字符串值也必须用双引号括起来。
  • JSON 不支持函数、undefined、Symbol 等 JavaScript 特定的类型。

参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON

本页目录