Indent JSON with JavaScript
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!
Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...
Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user. One of those simple APIs the Vibration API. The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...
One of my favorite Firefox plugins is called LinkAlert. LinkAlert shows the user an icon when they hover over a special link, like a link to a Microsoft Word DOC or a PDF file. I love that warning because I hate the surprise...
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.
You can also format a JSON file in the terminal with a single command.