isJsonString('{ "Id": 1, "Name": "Coke" }')
应该是正确的
isJsonString('foo')
isJsonString('<div>foo</div>')
应该为假。
我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。
isJsonString('{ "Id": 1, "Name": "Coke" }')
应该是正确的
isJsonString('foo')
isJsonString('<div>foo</div>')
应该为假。
我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。
当前回答
使用JSON.parse这样的JSON解析器:
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
其他回答
在prototypeJS中,我们有方法isJSON。你可以试试。甚至json也可能有所帮助。
"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
// -> true
我从开头的注释推断,用例描述的是响应是HTML还是JSON。在这种情况下,当您确实收到JSON时,您可能应该解析它并在代码中的某个位置处理无效JSON。除此之外,我想如果您的浏览器收到了JSON但无效的JSON,您会希望得到通知(用户也会通过代理收到一些有意义的错误消息)!
因此,为JSON执行完整的正则表达式是不必要的(根据我的经验,对于大多数用例来说,这是不必要的)。你可能会更好地使用下面的方法:
function (someString) {
// test string is opened with curly brace or machine bracket
if (someString.trim().search(/^(\[|\{){1}/) > -1) {
try { // it is, so now let's see if its valid JSON
var myJson = JSON.parse(someString);
// yep, we're working with valid JSON
} catch (e) {
// nope, we got what we thought was JSON, it isn't; let's handle it.
}
} else {
// nope, we're working with non-json, no need to parse it fully
}
}
这应该节省你不得不异常处理有效的非json代码,同时照顾duff json。
如果你不想在任何地方执行try/catch,寻找一个单一的行程序,并且不介意使用异步函数:
const isJsonString = async str => ( await ((async v => JSON.parse(v))(str)).then(_ => true).catch(_ => false) );
await isJsonString('{ "Id": 1, "Name": "Coke" }'); // true
await isJsonString('foo'); // false
await isJsonString('<div>foo</div>'); // false
if(resp) {
try {
resp = $.parseJSON(resp);
console.log(resp);
} catch(e) {
alert(e);
}
}
希望这也适用于你
你当然可以用try catch来检查它是否是一个有效的JSON
在Firfox Quantom 60
在函数中使用函数来测试JSON,并使用该输出来验证字符串。听一个例子。
function myfunction(text){
//function for validating json string
function testJSON(text){
try{
if (typeof text!=="string"){
return false;
}else{
JSON.parse(text);
return true;
}
}
catch (error){
return false;
}
}
//content of your real function
if(testJSON(text)){
console.log("json");
}else{
console.log("not json");
}
}
//use it as a normal function
myfunction('{"name":"kasun","age":10}')