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(str)的IsJsonString(str)函数在我的例子中不起作用。 我试图从GraphiQL验证json输出,它总是返回false。幸运的是,isJSON工作得更好:
var test = false;
$('body').on('DOMSubtreeModified', '.resultWrap', function() {
if (!test) {
var resultWrap = "{" + $('#graphiql .resultWrap').text().split("{").pop();
if isJSON(resultWrap) {test = !test;}
console.log(resultWrap);
console.log(resultWrap.isJSON());
}
});
样例输出:
THREE.WebGLRenderer 79
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 true
其他回答
你可以使用javascript的eval()函数来验证它是否有效。
e.g.
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。解析函数来自json.org:
try {
json = JSON.parse(jsonString);
} catch (exception) {
json = null;
}
if (json) {
//this is json
}
希望这能有所帮助。
警告:如果有人添加了恶意的JS代码,eval()是危险的,因为它会执行它。确保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, eval将抛出异常。
保持简单
函数isValidJsonString(测试器) / /早期现有 If (/^\s*$|undefined/.test(tester) || !(/number|object|array|string|boolean/。测试(typeof测试仪))) { 返回错误; }; //通过try catch进行解析 返回true; };
我来得太晚了。这就是我最后做的事。 使用快速的regex预检查可以大大提高性能
if(/^\s*(\{|\[)/.test(str)){
try{
JSON.parse(str)
// do something here, or return obj/true
}catch(e){
// do nothing or return false
}
}
正则表达式将检查字符串是否以[或{开头。 这将消除大多数错误情况(不是全部)。 下面是一个快速的性能测试https://jsbench.me/awl6fgn8jb/1
最坏的情况下,这可能比直接使用try慢10-15%,最坏的情况意味着所有字符串都是有效的json字符串。
最好的情况下这比纯try快99%,最好的情况下意味着所有字符串都是无效的json。
我知道我问这个问题已经晚了3年,但我还是想插话。
虽然Gumbo的解决方案工作得很好,但它不能处理一些没有引发JSON异常的情况。解析({非JSON})
我也更喜欢同时返回解析后的JSON,这样调用代码就不必再次调用JSON.parse(jsonString)。
这似乎很适合我的需求:
/**
* If you don't care about primitives and only objects then this function
* is for you, otherwise look elsewhere.
* This function will return `false` for any valid json primitive.
* EG, 'true' -> false
* '123' -> false
* 'null' -> false
* '"I'm a string"' -> false
*/
function tryParseJSONObject (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};
我从开头的注释推断,用例描述的是响应是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。