类似的情况。
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
该解决方案不应包含try/catch。我们中的一些人打开了"对所有错误的中断",他们不喜欢调试器对那些无效的JSON字符串进行中断。
你可以使用javascripteval()函数来验证它是否有效。
例如
var jsonString = '{ "Id": 1, "Name": "Coke" }';
var json;
try {
json = eval(jsonString);
} catch (exception) {
//It's advisable to always catch an exception since eval() is a javascript executor...
json = null;
}
if (json) {
//this is json
}
另外,你可以使用json.org的JSON.parse
函数。
try {
json = JSON.parse(jsonString);
} catch (exception) {
json = null;
}
if (json) {
//this is json
}
希望这有帮助。
警告。eval()
是*危险的,如果有人添加了恶意的JS代码,因为它会执行它。确保JSON字符串是值得信赖的,也就是说,你从一个值得信赖的来源得到它。
编辑对于我的第一个解决方案,建议这样做。
try {
json = eval("{" + jsonString + "}");
} catch (exception) {
//It's advisable to always catch an exception since eval() is a javascript executor...
json = null;
}
为了保证JSON性。如果 "jsonString "不是纯JSON,评估将抛出一个异常。