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!
使用XML和JavaScript是一场噩梦,这就是为什么JSON在开发社区中已成为黄金的原因。 地狱,我什至编写了一个函数,使用JavaScript将XML转换为JSON 。 如果要将现有对象转换为格式正确的JSON,可以使用JSON.stringify(obj)
,但是您已经知道这一点。 您可能不知道的是,从对象生成JSON时可以进行漂亮的格式化!
The secret is using the third JSON.stringify
argument which represents the space indentation levels:
秘诀是使用第三个JSON.stringify
参数,它表示空间缩进级别:
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!
结果JSON表示将被格式化并缩进两个空格!