我有一个简单的AJAX调用,服务器将返回一个带有有用数据的JSON字符串或一个由PHP函数mysql_error()产生的错误消息字符串。如何测试该数据是JSON字符串还是错误消息。
使用一个名为isJSON的函数会很好,就像你可以使用instanceof函数来测试某个东西是否是数组一样。
这就是我想要的:
if (isJSON(data)){
//do some data stuff
}else{
//report the error
alert(data);
}
你可以尝试解码它并捕获异常(本机或json2.js):
try {
newObj = JSON.parse(myJsonString);
} catch (e) {
console.log('Not JSON');
}
但是,我建议将响应始终设置为有效的JSON。如果你从你的MySQL查询中得到一个错误,简单地发送回JSON错误:
{"error":"The MySQL error string."}
然后:
if (myParsedJSON.error) {
console.log('An error occurred: ' + myParsedJSON.error);
}
我用了这个(有点混合了不同的答案,但不管怎样):
const isJSON = str => {
If (typeof STR === 'string'){
尝试{
JSON.parse (str)
还真
}捕捉(e) {
}
}
返回假
}
[null, undefined, false, true, [], {},
”,“asdf ', '{}', '[]', "{\" abc \”:2}”、“{\“abc \”,\“2 \“}”)
.map(el => {
console.log(' [>${el}<] - ${isJSON(el)} ')
})
console.log ('-----------------')