Products
GG网络技术分享 2025-03-18 16:17 0
后端返回数据之后,往往需要使用JS在前端对数据进行判断,就比如说判断返回的数据到底是什么类型,有数组/对象/JSON等等,那么今天我就给大家分享一下该如何判断数据是否为JSON格式的。
function shijson(str) {
if (typeof str == \'string\') {
try {
var obj=JSON.parse(str);
if(typeof obj == \'object\' && obj ){
return true;
}else{
return false;
}
} catch(e) {
console.log(\'error:\'+str+\'!!!\'+e);
return false;
}
}
}
将上面这段代码写到Script标签里面,然后通过调用函数shijson()。
完整演示:
<script>
if()shijson()){
console.log(\'是JSON数据\');
}else{
console.log(\'不是JSON数据\');
}
</script>Demand feedback