This question already has an answer here: This question already has an answer here: How can I beautify JSON programmatically? [duplicate] (1 answer) Closed 2 years ago.admin管理员组文章数量:1127935
Possible Duplicate:
How can I beautify JSON programmatically?
I know how to generate JSON from an object using JSON.stringify, or in my case the handy jQuery JSON from Google Code.
Now this works fine, but the output is hard to read for humans. Is there an easy way, function, or whatever to output a neatly formatted JSON file?
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]
}
}
E.g., 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, for example, not Prototype, YUI, or whatever.
Share Improve this question edited Jan 7, 2023 at 15:51 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Aug 18, 2010 at 18:43 Ben ClaytonBen Clayton 82.2k26 gold badges123 silver badges129 bronze badges 3- Maybe this will help: jsoneditoronline.org – invot Commented Mar 2, 2016 at 19:39
- Now you know why many prefer XML instead of JSON. Its much more readable. – Herman Van Der Blom Commented Dec 1, 2021 at 13:35
- 1 @HermanVanDerBlom, a one-line XML would not be human readble either. – Mihamina Rakotomandimby Commented Jun 21, 2023 at 5:25
1 Answer
Reset to default 1264JSON.stringify
takes more optional arguments.
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?
It 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. For display purposes, put the output in a <pre>
tag to get newlines to show.
本文标签: JavaScript How can I generate formatted easytoread JSON straight from an objectStack Overflow
版权声明:本文标题:JavaScript: How can I generate formatted easy-to-read JSON straight from an object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736710060a1948892.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论