JavaScript 提供了内置的 JSON 对象来处理 JSON 数据的解析和序列化,还允许对象自定义它们的序列化行为通过 toJSON
方法。
将 JavaScript 值转换为 JSON 字符串。
const obj = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// 输出: '{"name":"John","age":30,"city":"New York"}'
参数:
// 使用替换函数
function replacer(key, value) {
if (typeof value === 'string') {
return undefined; // 过滤掉所有字符串值
}
return value;
}
const filtered = JSON.stringify(obj, replacer);
console.log(filtered); // 输出: '{"age":30}'
// 使用缩进
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
/*
输出:
{
"name": "John",
"age": 30,
"city": "New York"
}
*/
将 JSON 字符串解析为 JavaScript 值。
const jsonStr = '{"name":"John","age":30,"city":"New York"}';
const parsedObj = JSON.parse(jsonStr);
console.log(parsedObj.name); // 输出: "John"
参数:
// 使用reviver函数
const reviver = (key, value) => {
if (key === 'age') return value + 1; // 年龄加1
return value;
};
const modified = JSON.parse(jsonStr, reviver);
console.log(modified.age); // 输出: 31
如果一个对象有 toJSON
方法,JSON.stringify()
会调用它并使用其返回值而不是原始对象进行序列化。
const person = {
name: "Alice",
age: 25,
toJSON: function() {
return {
fullName: this.name + " Smith",
yearsOld: this.age
};
}
};
console.log(JSON.stringify(person));
// 输出: '{"fullName":"Alice Smith","yearsOld":25}'
许多内置对象如 Date 已经有自己的 toJSON
方法:
const date = new Date();
console.log(date.toJSON()); // 输出ISO格式的日期字符串
console.log(JSON.stringify(date)); // 同上
JSON.stringify()
会忽略以下属性:
循环引用会导致错误:
const obj = {};
obj.self = obj;
JSON.stringify(obj); // 报错: TypeError: Converting circular structure to JSON
可以使用 try-catch
处理可能的解析错误:
try {
JSON.parse('不是有效的JSON');
} catch (e) {
console.error('解析错误:', e);
}
这些 JSON 处理方法是在 JavaScript 中处理数据交换和序列化的强大工具。