如何以编程方式美化JSON? [重复]

这篇博客介绍了如何以编程和手动方式美化JSON。对于编程格式化,提到了许多现代浏览器(包括IE8)支持的方法,以及json2.js库。手动格式化时推荐使用JSON Lint,它能同时美化和验证JSON。另外,文章还提到了为频繁处理JavaScript的开发者构建自定义CLI美化器的可能性。
摘要由CSDN通过智能技术生成

本文翻译自:How can I beautify JSON programmatically? [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

Do you know of any "JSON Beautifier" for JavaScript? 你知道JavaScript的“JSON Beautifier”吗?

From

{"name":"Steve","surname":"Jobs","company":"Apple"}

To

{
  "name" : "Steve",
  "surname" : "Jobs",
  "company" : "Apple"
}

Example

some_magic(jsonObj); // return beautified JSON

#1楼

参考:https://stackoom.com/question/AyFC/如何以编程方式美化JSON-重复


#2楼

Programmatic formatting solution: 编程格式化解决方案:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string: 许多现代浏览器(包括IE8)支持的JSON.stringify方法可以输出一个美化的JSON字符串:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js , for supporting older browsers. 此方法也包含在json2.js中 ,用于支持旧版浏览器。

Manual formatting solution 手动格式化方案

If you don't need to do it programmatically, Try JSON Lint . 如果您不需要以编程方式执行此操作,请尝试JSON Lint Not only will it prettify your JSON, it will validate it at the same time. 它不仅会美化你的JSON,它还会同时验证它。


#3楼

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently. 对于开发人员更频繁地破解(缩小或混淆)JavaScript,这可能是有趣的。

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. 您可以在5分钟内构建自己的CLI JavaScript美化器,并在命令行中使用它。 You'll need Mozilla Rhino , JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up. 你需要Mozilla Rhino ,一些在线可用的JS美化器的JavaScript文件,小黑客和一个脚本文件来包装它。

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript . 我写了一篇文章解释了这个过程: 用JavaScript实现的命令行JavaScript美化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值