已复制
全屏展示
复制代码

JavaScript之JSON处理


· 1 min read

序列化

var xiaoming = {
  name: '小明',
  age: 14,
  gender: true,
  height: 1.65,
  grade: null,
  'middle-school': '\"W3C\" Middle School',
  skills: ['JavaScript', 'Java', 'Python', 'Lisp']
};
var s = JSON.stringify(xiaoming);
// {"name":"小明","age":14,"gender":true,"height":1.65,"grade":null,"middle-school":"\"W3C\" Middle School","skills":["JavaScript","Java","Python","Lisp"]}


// 参数1:对象本身
// 参数2:选择要序列化的属性字段,为 null 表示序列化所有字段
// 参数3:美化输出时,每一行的空格数
JSON.stringify(xiaoming, ['name', 'skills'], '  ');
// '{\n  "name": "小明",\n  "age": 14,\n  "gender": true,\n  "height": 1.65,\n  "grade": null,\n  "middle-school": "\\"W3C\\" Middle School",\n  "skills": [\n    "JavaScript",\n    "Java",\n    "Python",\n    "Lisp"\n  ]\n}'



// 定义 toJSON 方法序列化
var xiaoming = {
    name: '小明',
    age: 14,
    gender: true,
    height: 1.65,
    toJSON: function () {
        return {   // 只输出name和age,并且改变了key:
            'Name': this.name,
            'Age': this.age
        };
    }
};
JSON.stringify(xiaoming); // '{"Name":"小明","Age":14}'

反序列化

JSON.parse('[1,2,3,true]');             // [1, 2, 3, true]
JSON.parse('{"name":"小明","age":14}');  // Object {name: '小明', age: 14}
JSON.parse('true');                     // true
JSON.parse('123.45');                   // 123.45
🔗

文章推荐