1.有时我们需要判断JSON格式的数据是否正确,这时可以使用Javascript的JSON.parse() 来进行判断,之后可以将不符合JSON格式规范的数据通过try{}catch{} 捕获
try{
let data = {
"name": "brant",
"age": "22",
"sex": "男"
}
let dataNew = JSON.parse(data)
console.log("JSON格式符合规范")
}catch{
console.log("JSON格式不符合规范")
}
2.JSON格式的数据类型有许多,因此为了区分不同的JSON数据,可以借助通过typeof xxx ,比如
1
{
"name": "brant",
"age": "22",
"sex": "男"
}
2
{
"name": "brant",
"age": "22",
"sex": "男",
"person": ["brant","22","男"]
}
3
{
"name": "brant",
"age": "22",
"sex": "男",
"person": ["brant","22","男"],
"person": {
"name": "brant",
"age": "22",
"sex": "男",
"person": ["brant","22","男"],
}
}
3.自定义JSON正则: 详情链接
var isJSON = function (str){
if (/^[\],:{}\s]*$/.test(str.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d (?:\.\d*)?(?:[eE][ \-]?\d )?/g, ']').
replace(/(?:^|:|,)(?:\s*\[) /g, ''))) {
return true;
}else{
return false;
}
}
|