如何测试字符串是否为JSON? [英] How to test if a string is JSON or not?
本文介绍了如何测试字符串是否为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的AJAX调用,服务器将返回带有用数据的JSON字符串或PHP函数 mysql_error()
生成的错误消息字符串。如何测试此数据是JSON字符串还是错误消息。
I have a simple AJAX call, and the server will return either a JSON string with useful data or an error message string produced by the PHP function mysql_error()
. How can I test whether this data is a JSON string or the error message.
使用名为 isJSON
的函数会很好,就像你可以使用函数 instanceof
来测试某些东西是否为数组。
It would be nice to use a function called isJSON
just like you can use the function instanceof
to test if something is an Array.
这就是我想要的:
if (isJSON(data)){
//do some data stuff
}else{
//report the error
alert(data);
}
推荐答案
使用JSON.parse
Use JSON.parse
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
这篇关于如何测试字符串是否为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文