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


    一.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), 将没有空格
    1. const jsonObj = {
    2. "name": "牙膏",
    3. age: 45,
    4. "count": 10,
    5. "orderDetail": 32143214214,
    6. "orderId": 78909890,
    7. "more": {
    8. "desc": "描述"
    9. }
    10. }
    11. // 筛选数据
    12. console.log(JSON.stringify(jsonObj, ['name', 'age']))//{"name":"牙膏","age":45}
    13. const jsonString = JSON.stringify(jsonObj, function (key, value) {
    14. if (typeof value === 'string') {
    15. return undefined
    16. }
    17. return value
    18. })
    19. //{"age":45,"count":10,"orderDetail":32143214214,"orderId":78909890,"more":{}}
    20. console.log(jsonString)
    21. /**
    22. * {
    23. "name": "牙膏",
    24. "age": 45,
    25. "count": 10,
    26. "orderDetail": 32143214214,
    27. "orderId": 78909890,
    28. "more": {
    29. "desc": "描述"
    30. }
    31. }
    32. */
    33. // 格式化数据
    34. console.log(JSON.stringify(jsonObj, null, '\t'))

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

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

    1. let product = {
    2. "name": "牙膏",
    3. age: 45,
    4. "count": 10,
    5. "orderDetail": 32143214214,
    6. "orderId": 78909890,
    7. "more": {
    8. "desc": "描述"
    9. },
    10. toJSON() {
    11. return {
    12. name: '哇哈哈'
    13. }
    14. }
    15. }
    16. /** 打印结果:
    17. * {
    18. "name": "哇哈哈"
    19. }
    20. */
    21. console.log(JSON.stringify(product, null, '\t'))

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

    1. let jsonStr = `{
    2. "name": "牙膏",
    3. "count": 10,
    4. "orderDetail": 32143214214,
    5. "orderId": 78909890,
    6. "more": {
    7. "desc": "描述"
    8. }
    9. }`
    10. const obj = JSON.parse(jsonStr, function (k, value) {
    11. console.log('key:', k, 'this:', this, 'value:', value)
    12. if (typeof value === 'string') {
    13. return undefined
    14. }
    15. return value
    16. })
    17. // {"count":10,"orderDetail":32143214214,"orderId":78909890,"more":{}}
    18. console.log(JSON.stringify(obj))

  • 相关阅读:
    acwing算法基础之数学知识--高斯消元法求解线性方程组
    提升 React 应用的安全性:从这几点入手
    MySQL语言分类
    四、图片特效
    实施 ECM 系统的 6 大挑战——以及如何避免它们
    ISO7816-3标准ATR解析
    网页翻译软件-网页自动采集翻译软件免费
    关于如何检查一个进程是否存活
    React 18 + Hooks +Ts 开发中遇到的问题及解决方案!
    博客系统页面设计
  • 原文地址:https://blog.csdn.net/qq_42750608/article/details/133320415