JSON.stringify使用

基本使用

JSON.stringify(value[, replacer [, space]])

value
将要序列化成 一个JSON 字符串的值。
replacer 可选
如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为null或者未提供,则对象所有的属性都会被序列化;关于该参数更详细的解释和示例,请参考使用原生的 JSON 对象一文。
space 可选
指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;如果该参数没有提供(或者为null)将没有空格。
function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);
JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'

JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
// '{            \
//     "uno": 1, \
//     "dos": 2  \
// }'

运用技巧

打印对象

let categories = [
    {
        id:'animals',
        'parent':null
    },
    {
        id:'mammals',
        'parent':'animals'
    },
    {
        id:'cats',
        'parent':'mammals'
    },
    {
        id:'dogs',
        'parent':'mammals'
    },
    {
        id:'chihuahua',
        'parent':'dogs'
    },
    {
        id:'labrador',
        'parent':'dogs'
    },
    {
        id:'persian',
        'parent':'cats'
    },
    {
        id:'siamese',
        'parent':'cats'
    }
]

let makeTree = (categories,parent) => {
    let node = {}

    categories.filter(c => c.parent === parent)
    .forEach(c => 
        node[c.id] = makeTree(categories,c.id)
    )

    return node
}

//普通打印
console.log( makeTree(categories,null)) //{ animals: { mammals: { cats: [Object], dogs: [Object] } } }

//加上JSON.stringify
console.log(
    JSON.stringify(
        makeTree(categories,null)
    )
)
//{"animals":{"mammals":{"cats":{"persian":{},"siamese":{}},"dogs":{"chihuahua":{},"labrador":{}}}}}

//加上间距
console.log(
    JSON.stringify(
        makeTree(categories,null)
        ,null
        ,2
    )
)

/*{
  "animals": {
    "mammals": {
      "cats": {
        "persian": {},
        "siamese": {}
      },
      "dogs": {
        "chihuahua": {},
        "labrador": {}
      }
    }
  }
}*/

猜你喜欢

转载自www.cnblogs.com/pluslius/p/10163977.html