当前位置:   article > 正文

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

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))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/733845
推荐阅读
相关标签
  

闽ICP备14008679号