本文翻译自: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>
标记中以获取要显示的换行符。