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!
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event...
Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors.
The CSS
The above CSS is extremely basic.
Note: For this tutorial, I'm using version1 of the Google Translate API. A newer REST-based version is available.
In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...
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.