跳到主要内容

JSON 操作

JavaScript 中处理 JSON 的常用方法。

JSON.parse() - 解析 JSON

// 字符串转对象
const jsonStr = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonStr);

console.log(obj.name); // 'Alice'
console.log(obj.age); // 25

// 带解析回调
const obj2 = JSON.parse(jsonStr, (key, value) => {
if (key === 'age') return value + 1; // 年龄 +1
return value;
});
console.log(obj2.age); // 26

JSON.stringify() - 序列化 JSON

const obj = { name: 'Alice', age: 25 };

// 对象转字符串
const jsonStr = JSON.stringify(obj);
console.log(jsonStr); // '{"name":"Alice","age":25}'

// 格式化输出
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
// {
// "name": "Alice",
// "age": 25
// }

// 只序列化指定属性
const selected = JSON.stringify(obj, ['name'], 2);
console.log(selected); // '{"name":"Alice"}'

处理特殊值

const obj = {
name: 'Alice',
age: 25,
active: true,
hobby: null,
address: undefined,
fn: () => {},
date: new Date()
};

JSON.stringify(obj);
// {"name":"Alice","age":25,"active":true,"hobby":null}
// undefined 和函数会被忽略
// Date 会被转成 ISO 字符串

深拷贝

// 使用 JSON 方法深拷贝
const original = { a: 1, b: { c: 2 } };
const copy = JSON.parse(JSON.stringify(original));

copy.b.c = 3;
console.log(original.b.c); // 2

// 限制:
// - 不能处理函数
// - 不能处理 undefined
// - 不能处理 Date(会变成字符串)
// - 不能处理 RegExp
// - 不能处理循环引用

安全解析

// 防止解析错误
function safeParse(jsonStr, defaultValue = {}) {
try {
return JSON.parse(jsonStr);
} catch (e) {
console.error('JSON 解析失败:', e);
return defaultValue;
}
}

// 使用
const data = safeParse('{"invalid": json}');
console.log(data); // {}

LocalStorage 存储对象

// 存储
const user = { name: 'Alice', age: 25 };
localStorage.setItem('user', JSON.stringify(user));

// 读取
const stored = JSON.parse(localStorage.getItem('user'));
console.log(stored.name); // 'Alice'

// 安全读取
function getStorage(key, defaultValue = null) {
const str = localStorage.getItem(key);
if (!str) return defaultValue;
try {
return JSON.parse(str);
} catch (e) {
return defaultValue;
}
}

格式化 JSON

// 美化输出
function formatJson(json, indent = 2) {
return JSON.stringify(json, null, indent);
}

// 压缩输出
function minifyJson(json) {
return JSON.stringify(json);
}

// 使用
const obj = { a: 1, b: { c: 2, d: 3 } };
console.log(formatJson(obj));
// {
// "a": 1,
// "b": {
// "c": 2,
// "d": 3
// }
// }

处理循环引用

// 循环引用会导致 JSON.stringify 报错
const obj = { name: 'Alice' };
obj.self = obj;

try {
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
} catch (e) {
console.error(e.message);
}

// 解决方案:使用 replacer 函数
const seen = new WeakSet();
const json = JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
});

console.log(json); // {"name":"Alice","self":"[Circular]"}