校验字符串是否是JSON格式,将不规则展示的json格式的字符串进行规则展示(json格式化)

var str = {"code": "","svcname": "","version": "","component": "","category": "","requestMsg": [{"fieldName": "userName","type": "simple","required": "true"},{"fieldName": "age","type": "simple","required": "true"}]}

一、校验字符串是否是JSON格式:

function isJsonFormat(str) {
    try {
        $.parseJSON(str);
    } catch (e) {
        return false;
    }
    return true;
}


二、将json格式的字符串格式化输出,先将json字符串转为对象,然后将此对象以json格式化输出:


JSON.stringify(JSON.parse(json), null, "\t")

JSON.stringify(JSON.parse(json), null, 4)



PS:\t:代表缩进一个tab;4:代表缩进4个空格


格式化后的输出:
{
	"code": "",
	"svcname": "",
	"version": "",
	"component": "",
	"category": "",
	"requestMsg": [
		{
			"fieldName": "userName",
			"type": "simple",
			"required": "true"
		},
		{
			"fieldName": "age",
			"type": "simple",
			"required": "true"
		}
	]
}


推荐一个好的JSON在线解析工具:http://www.json.cn/




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值