目录
JSON序列化
const obj = {
name: "John",
age: 30,
city: "New York",
};
// 基本用法,将对象转换为 JSON 字符串
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// 使用 replacer 函数进行自定义转换
const replacer = (key, value) => {
if (typeof value === "number" && value > 25) {
return value + 1;
}
return value;
};
const jsonStringWithReplacer = JSON.stringify(obj, replacer);
console.log(jsonStringWithReplacer);
// 使用 space 参数来控制缩进
const jsonStringWithIndentation = JSON.stringify(obj, null, 4);
console.log(jsonStringWithIndentation);
obj.toJSON=function(){
return {
fullName:this.name,
yearsOld:this.age,
location:this.city
}
}
const jsonString1= JSON.stringify(obj);
console.log(jsonString1);
JSON反序列化
// 假设我们有一个JSON格式的字符串
const jsonString =
'{"name": "Alice", "age": 25, "isStudent": true, "courses": ["Math", "Science