Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深入理解 JSON #31

Open
ly2011 opened this issue May 6, 2018 · 0 comments
Open

深入理解 JSON #31

ly2011 opened this issue May 6, 2018 · 0 comments
Labels

Comments

@ly2011
Copy link
Owner

ly2011 commented May 6, 2018

深入理解JSON

将JS数据结构转换为JSON字符串:J SON.stringify

语法:JSON.stringify(value[,replacer[, space]])

基本使用-一个参数

传入一个JSON格式的JS对象或数组:

// 对象
JSON.stringify({"name": "Good Man", "age": 18})
// '{"name": "Good Man", "age": 18}'

// 数组
JSON.stringify([1, 2, 3, "4"])
// '[1, 2, 3, "4"]'

第二个参数是一个函数或者是一个数组或者null或者未提供

  • 如果该参数是一个参数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理
var friend = {
  "firstName": "Good",
  "lastName": "Man",
  "phone": "1234567",
  "age": 18
}
var friendAfter = JSON.stringify(friend, function (key, value) {
  if (key === 'phone') {
    return "(000)" + value;
  } else if (typeof value === 'number') {
    return 10 + value;
  } else {
    return value; // 如果你把这个else分句(即是缺少最后的return value),那么结果会是 undefined
  }
})
console.log(friendAfter);
// {"firstName": "Good", "lastName": "Man", "phone": "(000)1234567", "age": 28}

如果上面的传入不是键值对的对象形式,而是数组形式的,比如上面传入的是 var friend = ["Jack", "Rose"], 如果是数组形式,那么 key 是索引值,而 value 是这个数组项,记得要在函数内部返回value,不然会出错。

  • 如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的JSON字符串中,而这个数组中存在但是源JS对象中不存在的属性会被忽略,不会报错
var friend = {
  "firstName": "Good",
  "lastName": "Man",
  "address": "1234567",
  "age": 18,
  "phone": {"home": "1234567", "work": "7654321"}
}
var friendAfter = JSON.stringify(friend, ["firstName", "address", "phone"])
console.log(friendAfter);
// {"firstName": "Good", "address": "1234567","phone": {}}
// 由于 phone 对象的属性不在数组中,所以没有被序列化出来
  • 如果该参数为 null 或者未提供,则对象所有的属性都会被序列化

参考文档

  1. 深入理解JSON
  2. 深度使用 JSON.stringify()
@ly2011 ly2011 added the JS label May 6, 2018
@ly2011 ly2011 changed the title 深入理解 JSON.stringify() 深入理解 JSON May 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant