Indent JSON with JavaScript

By  on  

Working with XML and JavaScript is a nightmare, which is why JSON has become gold in the development community.  Hell, I even wrote a function to turn XML to JSON with JavaScript.  If you want to turn an existing object into well formatted JSON, you can you JSON.stringify(obj), but you already know that.  What you may not know is that you can do pretty formatting when generating JSON from objects!

The secret is using the third JSON.stringify argument which represents the space indentation levels:

var formatted = JSON.stringify(myObject, null, 2);

/*
	Result:

	{
		"myProp": "myValue",
		"subObj": {
			"prop": "value"
		}
	}

*/

The resulting JSON representation will be formatted and indented with two spaces!

Recent Features

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    Animated AJAX Record Deletion Using jQuery

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with jQuery JavaScript. The PHP - Content & Header The following snippet goes at the...

  • By
    Create an Animated Sliding Button Using MooTools

    Buttons (or links) are usually the elements on our sites that we want to draw a lot of attention to. Unfortunately many times they end up looking the most boring. You don't have to let that happen though! I recently found a...

Discussion

  1. MaxArt

    For more advanced formatting, I’ve developed a tool for the intent:
    https://github.com/MaxArt2501/json-fmt
    It works a client library or a server module for node/io.js, has a CLI, and a Grunt and a Gulp plugin.

    Of course, if you need speed just use JSON.stringify.

    Sorry for the self-promotion.

  2. You can also format a JSON file in the terminal with a single command.

    python -m json.tool unformatted.json > formatted.json

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!