Javascript: How to generate formatted easy-to-read JSON straight from an object? [duplicate]

末鹿安然 提交于 2019-11-26 07:52:38

问题


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 (https://github.com/krinkle/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?

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 - e.g. not prototype or YUI or whatever.


回答1:


JSON.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?

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.



来源:https://stackoverflow.com/questions/3515523/javascript-how-to-generate-formatted-easy-to-read-json-straight-from-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!