JSON.stringify使用
发布时间:2020-12-16 18:42:46 所属栏目:百科 来源:网络整理
导读:基本使用 JSON.stringify(value[,replacer [,space]]) value将要序列化成 一个JSON 字符串的值。replacer 可选如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的
基本使用
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": 2n}‘ JSON.stringify({ uno: 1,dos : 2 },‘t‘) // ‘{ // "uno": 1,// "dos": 2 // }‘ 运用技巧
let categories = [ { id:‘animals‘,‘parent‘:null },{ id:‘mammals‘,‘parent‘:‘animals‘ },{ id:‘cats‘,‘parent‘:‘mammals‘ },{ id:‘dogs‘,{ id:‘chihuahua‘,‘parent‘:‘dogs‘ },{ id:‘labrador‘,{ 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),2 ) ) /*{ "animals": { "mammals": { "cats": { "persian": {},"siamese": {} },"dogs": { "chihuahua": {},"labrador": {} } } } }*/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |