How can I beautify JSON programmatically?

This question already has an answer here:

  • How can I pretty-print JSON using JavaScript? 20 answers

  • Programmatic formatting solution:

    The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

    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.

    Manual formatting solution

    If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.


    Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

    You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. 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.

    I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

    链接地址: http://www.djcxy.com/p/1318.html

    上一篇: 在JavaScript中美化JSON数组

    下一篇: 如何以编程方式美化JSON?