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
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    CSS Fixed Positioning

    When you want to keep an element in the same spot in the viewport no matter where on the page the user is, CSS's fixed-positioning functionality is what you need. The CSS Above we set our element 2% from both the top and right hand side of the...

  • By
    Using Opacity to Show Focus with jQuery

    A few days back I debuted a sweet article that made use of MooTools JavaScript and opacity to show focus on a specified element. Here's how to accomplish that feat using jQuery. The jQuery JavaScript There you have it. Opacity is a very simple but effective...

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!