使用JavaScript缩进JSON

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表示将被格式化并缩进两个空格!

翻译自: https://davidwalsh.name/indent-json-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值