一.JSON.stringify

  1. 语法: JSON.stringify(value[, replacer[,space]])
  2. 第二个参数replacer: 过滤属性或者处理值
  3. 第三个参数space: 美化输出格式

第一个参数: 对象object等

第二个参数replacer:

  1. 如果该参数是一个函数: 则在序列化的过程中,被序列化的值的每个属性都会经过该函数的转换和处理
  2. 如果该函数是一个数组: 则只有包含在这个数组中的属性名才会被序列化到最终的JSON字符串中
  3. 如果该参数是null或者未提供,则对象所有的属性都会被序列化

第三个参数space:

  1. 如果参数是数字: 它代表有多少的空格; 上限为10. 该值若小于1,则意味着没有空格
  2. 如果该参数为字符串:(当字符串长度超过10个字母,取其前10个字母), 该字符串将被作为空格
  3. 如果该参数没有提供:(或者null), 将没有空格
const jsonObj = {
    "name": "牙膏",
    age: 45,
    "count": 10,
    "orderDetail": 32143214214,
    "orderId": 78909890,
    "more": {
        "desc": "描述"
    }
}
// 筛选数据
console.log(JSON.stringify(jsonObj, ['name', 'age']))//{"name":"牙膏","age":45}
const jsonString = JSON.stringify(jsonObj, function (key, value) {
    if (typeof value === 'string') {
        return undefined
    }
    return value
})
//{"age":45,"count":10,"orderDetail":32143214214,"orderId":78909890,"more":{}}
console.log(jsonString)
/**
 * {
    "name": "牙膏",
    "age": 45,
    "count": 10,
    "orderDetail": 32143214214,
    "orderId": 78909890,
    "more": {
        "desc": "描述"
    }
}
 */
// 格式化数据
console.log(JSON.stringify(jsonObj, null, '\t'))

JSON.stringify格式化数据美化显示效果(不呆板地一行显示)-LMLPHP

注意: 如果需求中有要求将json字符串显示为容易阅读的形式时应使用: JSON.stringify(对象变量xxobject, null, '\t')

二.toJSON: 拥有toJSON方法, toJSON会覆盖对象默认的序列化行为

let product = {
    "name": "牙膏",
    age: 45,
    "count": 10,
    "orderDetail": 32143214214,
    "orderId": 78909890,
    "more": {
        "desc": "描述"
    },
    toJSON() {
        return {
            name: '哇哈哈'
        }
    }
}
/** 打印结果:
 * {
	"name": "哇哈哈"
}
 */
console.log(JSON.stringify(product, null, '\t'))

JSON.stringify格式化数据美化显示效果(不呆板地一行显示)-LMLPHP

三.JSON.parse也有筛选数据的方法, 它的第二个参数函数reviver(k, v)

let jsonStr = `{
    "name": "牙膏",
    "count": 10,
    "orderDetail": 32143214214,
    "orderId": 78909890,
    "more": {
        "desc": "描述"
    }
}`

const obj = JSON.parse(jsonStr, function (k, value) {
    console.log('key:', k, 'this:', this, 'value:', value)
    if (typeof value === 'string') {
        return undefined
    }
    return value
})
// {"count":10,"orderDetail":32143214214,"orderId":78909890,"more":{}}
console.log(JSON.stringify(obj))

JSON.stringify格式化数据美化显示效果(不呆板地一行显示)-LMLPHP

09-27 10:48