【JavaScript】了解 JSON

认识 JSON

JSON → JavaScript Object Notation,一种 JavaScript 的对象表示法

JSON 的作用:进行前后端的数据交互

  1. JSON 就是对象格式的字符串,要用单引号 '' 将其括起来
  2. JSON 内的引号必须是双引号 ""
  3. JSON 内的属性名也必须用双引号括住;属性值只有字符串需要括住
let obj = {
    name: 'superman',
    age: 18
};
let json = '{"name":"superman","age":18}';

JSON 的方法

  • JSON 是 JS 的一个内置对象,有 stringify() & parse() 两个方法
  • 注意这两个是 JSON 的方法,所以要用 JSON. 调用

parse()

作用:JSON → 对象(英文 parse 是 “解析” 的意思)

JSON.parse(json);
let json = '{"name":"superman", "age":18}';
console.log('json', json); // json {"name":"superman", "age":18}

let obj = JSON.parse(json);
console.log('obj', obj); // obj {name: "superman", age: 18}

stringify()

作用:对象 → JSON(英文 stringify 是 “字符串化” 的意思)

JSON.stringify(obj);
const obj = {
    name: "superman",
    hobbies: ["basketball", "football"],
    age: 21,
};
console.log(JSON.stringify(obj)); // {"name":"superman","hobbies":["basketball","football"],"age":21}

处理特殊属性值:

  • 对于对象的特殊属性值:
const obj = {
    // 函数 → 直接忽略
    _function: function () {
        console.log("singing");
    },
    _undefined: undefined, // undefined → 直接忽略
    _null: null, // null → 返回 null
    _NaN: NaN, // NaN → 返回 null
    _Infinity1: Infinity, // Infinity → 返回 null
    _Infinity2: -Infinity, // -Infinity → 返回 null
    _RegExp: new RegExp(), // 正则 → 返回空对象 {}
    _Date: new Date(), // Date → 以字符串形式返回
};
console.log(JSON.stringify(obj));
// {"_null":null,"_NaN":null,"_Infinity1":null,"_Infinity2":null,"_RegExp":{},"_Date":"2022-08-23T15:14:06.581Z"}
function Person(name) {
    this.name = name;
}
Person.prototype.age = 21; // 原型的属性 → 直接忽略
const person = new Person("superman");
console.log(JSON.stringify(person)); // {"name":"superman"}

传入更多参数

const obj = {
    name: "superman",
    age: 21,
    gender: "male",
    address: "China",
};
console.log(JSON.stringify(obj, ["name", "gender"])); // {"name":"superman","gender":"male"}
const studentData = [{
    name: "张三", score: 90,
}, {
    name: "李四", score: 80,
}];
function formatData(key, value) {
    if (key === "score") {
        switch (true) {
            case value >= 90: return "A";
            case value >= 80: return "B";
            case value >= 70: return "C";
            case value >= 60: return "D";
            default: return "E";
        }
    }
    return value;
}
console.log(JSON.stringify(studentData, formatData)); // [{"name":"张三","score":"A"},{"name":"李四","score":"B"}]
  • 第 3 个参数为数字,表示输出的缩进距离
const obj = {
    name: "superman",
    hobbies: ["basketball", "football"],
    age: 21,
};
console.log(JSON.stringify(obj, null, 4)); // 缩进为 4 个空格
// {
//     "name": "superman",
//     "hobbies": [
//         "basketball",
//         "football"
//     ],
//     "age": 21
// }

自定义

const obj = {
    name: "superman",
    hobbies: ["basketball", "football"],
    age: 21,
    toJSON: function () { // 注意:不能使用 ES6 的简写 `toJSON(){}`
        return `${this.name}, ${this.hobbies}, ${this.age}`;
    },
};
console.log(JSON.stringify(obj)); // "superman, basketball,football, 21"

使用场景:

  • 配合 localStorage 使用:
const obj = { name: "superman" };
localStorage.setItem("obj", JSON.stringify(obj));
const objStr = localStorage.getItem("obj");
  • 深拷贝对象:
const obj = {
    name: "superman",
    hobbies: ["basketball", "football"],
    age: 21,
};
const objDeepcopy = JSON.parse(JSON.stringify(obj));
objDeepcopy.hobbies[0] = "swimming";
console.log(obj); // { name: 'superman', hobbies: [ 'basketball', 'football' ], age: 21 }
console.log(objDeepcopy); // { name: 'superman', hobbies: [ 'swimming', 'football' ], age: 21 }
  • JSON.stringify() 不能作用于循环结构的对象:
const obj = {
    name: "superman",
};
obj.myObj = obj; // 形成闭环
console.log(JSON.stringify(obj)); // TypeError: Converting circular structure to JSON

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...