最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】jquery的js中把json对象转换为格式化后的带缩进的json字符串

JSON crifan 1225浏览 0评论
折腾:
【已解决】本地搭建前端Web页面实现机器人问答的产品演示
期间,想要把js中console.log中打印出来的json对象
转换为json的字符串,且需要格式化后的带缩进的,方便查看的。
jquery json object to string
jquery – Convert Object to JSON string – Stack Overflow
JSON.stringify()
jquery – JSON Object to String – Stack Overflow
JSON.stringify()
jQuery JSON to String — SitePoint
jquery json object to formatted string
javascript – jquery display formatted json – Stack Overflow
Style or Format JSON Data in jQuery – DZone Web Dev
JSON.stringify() – JavaScript | MDN
Syntax
JSON.stringify(value[, replacer[, space]])
Parameters
value
The value to convert to a JSON string.
replacer Optional
A function that alters the behavior of the stringification process, or an array of Stringand Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space Optional
A String or Number object that’s used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it’s longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
JavaScript JSON.stringify() | 菜鸟教程
“语法
JSON.stringify(value[, replacer[, space]])
参数说明:
value:
必需, 要转换的 JavaScript 值(通常为对象或数组)。
replacer:
可选。用于转换结果的函数或数组。
如果 replacer 为函数,则 JSON.stringify 将调用该函数,并传入每个成员的键和值。使用返回值而不是原始值。如果此函数返回 undefined,则排除成员。根对象的键是一个空字符串:””。
如果 replacer 是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。当 value 参数也为数组时,将忽略 replacer 数组。
space:
可选,文本添加缩进、空格和换行符,如果 space 是一个数字,则返回值文本在每个级别缩进指定数目的空格,如果 space 大于 10,则文本缩进 10 个空格。space 有可以使用非数字,如:\t。”
【总结】
此处js的jquery中把json对象转换为json字符串,且带缩进的话:
本身js中就有够好用的函数了JSON.stringify,用于将json对象转换为字符串
所以jquery中没有单独再有类似函数。
而默认的话,JSON.stringify转换出来的json字符串不带缩进,可以加上参数:
var beautifiedJespnJsonStr = JSON.stringify(respJsonObj, null, '\t');
即可通过\t = tab去缩进。
嫌弃缩进宽度太多,换成2个空格:
var beautifiedJespnJsonStr = JSON.stringify(respJsonObj, null, 2);
console.log("beautifiedJespnJsonStr=%s", beautifiedJespnJsonStr);
效果就很好了:
(后续高亮后)

转载请注明:在路上 » 【已解决】jquery的js中把json对象转换为格式化后的带缩进的json字符串

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.171 seconds, using 22.14MB memory