分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

JSON.stringify使用

发布时间:2023-09-06 02:27责任编辑:傅花花关键词:gif

基本使用

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.stringifyconsole.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": {} ?????} ???} ?}}*/

JSON.stringify使用

原文地址:https://www.cnblogs.com/pluslius/p/10163977.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved