likes
comments
collection
share

JavaScript高级程序设计-摘要笔记-6

作者站长头像
站长
· 阅读数 22

关于JSON

1. JSON 对象

es5 定义了全局对象 JSON。支持的浏览器有 IE8+ 、Firefox 3.5+ 、Safari 4+、Chrome、Opera 10.5+

2. JSON.stringify()

JSON.stringify() 除了接受要序列化的对象外,还可以接受另外两个参数。第一个参数是一个过滤器,可以是一个数组或函数,第二个参数是一个选项,表示是否在JSON字符串中保留缩进。如:

var book = {
  title: 'Professional JS',
  authors: ['abc', 'def'],
  edition: 3,
  year: 2011
}

第一个参数是数组

var jsonText1 = JSON.stringify(book, ['title', 'edition'])
console.log(jsonText1) // '{"title":"Professional JS","edition":3}'

第一个参数是函数

var jsonText2 = JSON.stringify(book, function (key, value) {
  switch (key) {
    case 'authors':
      return value.join(',');
    case 'year':
      return 2016;
    case 'edition':
      return undefined;
    default:
      return value;
  }
})
console.log(jsonText2) // '{"title":"Professional JS","authors":"abc,def","year":2016}'

第二个参数用于控制结果中的缩进和空白符。如果是数值,则表示每个级别缩进的空格数,最大10,超过10 的值自动转换成10。如果是字符串,则用作缩进字符。字符串长度超过10,结果中将只出现前10个字符。会在结果字符串中插入换行符提高可读性。如:

var jsonText3 = JSON.stringify(book, null, 6)
console.log(jsonText3)
// '{
//       "title": "Professional JS",
//       "authors": [
//             "abc",
//             "def"
//       ],
//       "edition": 3,
//       "year": 2011
// }'
var jsonText4 = JSON.stringify(book, null, '--')
console.log(jsonText4)
// '{
// --"title": "Professional JS",
// --"authors": [
// ----"abc",
// ----"def"
// --],
// --"edition": 3,
// --"year": 2011
// }'

3. toJSON() 方法

可以给对象定义 toJSON() 方法,返回自身的 JSON 数据格式,此方法优先级最高如:

var book = {
  title: 'Professional JS',
  authors: ['abc', 'def'],
  edition: 3,
  year: 2011,
  toJSON: function () {
    return {
      name: 'wfc'
    }
  }
}
var jsonText = JSON.stringify(book, null, 1)
console.log(jsonText)
// '{
//  "name": "wfc"
// }'

注意: JSON.stringify() 处理的优先级为 toJSON() => 第二个参数 => 第三个参数。

4. JSON.parse()

JSON.parse() 接受另一个参数,该参数是一个函数,将在每个健值对上采用,类似于 JSON.stringify() 的过滤函数。如:

var book = {
  title: 'Professional JS',
  authors: ['abc', 'def'],
  edition: 3,
  year: 2011,
  releaseDate: new Date(2016,11,22)
}
var jsonText = JSON.stringify(book, null, 1)
console.log(jsonText)
// '
// json.html:48 {
//  "title": "Professional JS",
//  "authors": [
//   "abc",
//   "def"
//  ],
//  "edition": 3,
//  "year": 2011,
//  "releaseDate": "2016-12-21T16:00:00.000Z"
// }'
var copyBook = JSON.parse(jsonText, function (key, value) {
  if (key === 'releaseDate') {
    console.log(value) // '2016-12-21T16:00:00.000Z'
    return new Date(value)
  } else {
    return value
  }
})

JSON部分结束