Javascript:如何直接从对象生成格式化的易于阅读的JSON? [重复]

本文翻译自:Javascript: How to generate formatted easy-to-read JSON straight from an object? [duplicate]

Possible Duplicate: 可能重复:
How can I beautify JSON programmatically? 如何以编程方式美化JSON?

I know how to generate JSON from an object using JSON.stringify, or in my case the handy jquery-json from google code ( https://github.com/krinkle/jquery-json ). 我知道如何使用JSON.stringify从对象生成JSON,或者在我的情况下从google代码( https://github.com/krinkle/jquery-json )生成方便的jquery-json。

Now this works fine, but the output is hard to read for humans. 现在这种方法很好,但输出很难为人类阅读。 Is there an easy way / function / whatever to output a neatly formatted json file? 是否有简单的方法/功能/输出整齐格式的json文件?

This is what I mean: 这就是我的意思:

JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}); 

gives.. 使..

"{"a":1,"b":2,"c":{"d":1,"e":[1,2]}}"

I'd like something like this instead: 我喜欢这样的东西:

{
 "a":1,
 "b":2,
 "c":{
    "d":1,
    "e":[1,2]
 }
}

Eg with newlines and tabs added. 例如添加了换行符和标签。 It's much easier to read for larger documents. 阅读更大的文档要容易得多。

I'd like to do this ideally without adding any huge libraries - eg not prototype or YUI or whatever. 我想在没有添加任何大型库的情况下理想地执行此操作 - 例如,不是原型或YUI或其他任何东西。


#1楼

参考:https://stackoom.com/question/EkXz/Javascript-如何直接从对象生成格式化的易于阅读的JSON-重复


#2楼

JSON.stringify takes more optional arguments . JSON.stringify需要更多可选参数

Try: 尝试:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From: 从:

How can I beautify JSON programmatically? 如何以编程方式美化JSON?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. 应该在现代浏览器中工作,并且如果您需要对不支持JSON帮助程序函数的浏览器进行回退,它将包含在json2.js中 For display purposes, put the output in a <pre> tag to get newlines to show. 出于显示目的,将输出放在<pre>标记中以获取要显示的换行符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值