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;
}
其他回答
如果您正在处理来自AJAX(或XMLHttpRequest)调用的响应,对我来说有效的方法是检查响应内容类型,并相应地解析或不解析内容。
我从开头的注释推断,用例描述的是响应是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。
下面是我的工作代码:
function IsJsonString(str) {
try {
var json = JSON.parse(str);
return (typeof json === 'object');
} catch (e) {
return false;
}
}
使用JSON.parse这样的JSON解析器:
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
如果你有疑问,值是或不是json
function isStringified(jsonValue) { // use this function to check
try {
console.log("need to parse");
return JSON.parse(jsonValue);
} catch (err) {
console.log("not need to parse");
return jsonValue;
}
}
然后
const json = isStringified(stringValue);
if (typeof json == "object") {
console.log("string is a valid json")
}else{
console.log("string is not a valid json")
}