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字符串上中断。
当前回答
对于喜欢. net惯例中的“try”函数,它返回一个布尔值并处理一个包含结果的byref参数。如果不需要out参数,可以省略它,只使用返回值。
StringTests.js
var obj1 = {};
var bool1 = '{"h":"happy"}'.tryParse(obj1); // false
var obj2 = {};
var bool2 = '2114509 GOODLUCKBUDDY 315852'.tryParse(obj2); // false
var obj3 = {};
if('{"house_number":"1","road":"Mauchly","city":"Irvine","county":"Orange County","state":"California","postcode":"92618","country":"United States of America","country_code":"us"}'.tryParse(obj3))
console.log(obj3);
StringUtils.js
String.prototype.tryParse = function(jsonObject) {
jsonObject = jsonObject || {};
try {
if(!/^[\[{]/.test(this) || !/[}\]]$/.test(this)) // begin / end with [] or {}
return false; // avoid error handling for strings that obviously aren't json
var json = JSON.parse(this);
if(typeof json === 'object'){
jsonObject.merge(json);
return true;
}
} catch (e) {
return false;
}
}
ObjectUtils.js
Object.defineProperty(Object.prototype, 'merge', {
value: function(mergeObj){
for (var propertyName in mergeObj) {
if (mergeObj.hasOwnProperty(propertyName)) {
this[propertyName] = mergeObj[propertyName];
}
}
return this;
},
enumerable: false, // this is actually the default
});
其他回答
你可以使用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将抛出异常。
先评论一下。问题是关于不使用try/catch。 如果你不介意使用它,请阅读下面的答案。 这里我们只是使用regexp检查JSON字符串,它在大多数情况下都可以工作,而不是所有情况。
看看https://github.com/douglascrockford/JSON-js/blob/master/json2.js的450行
有一个regexp检查有效的JSON,类似于:
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
编辑:新版本的json2.js进行了比上面更高级的解析,但仍然基于regexp替换(来自@Mrchief的评论)
if(resp) {
try {
resp = $.parseJSON(resp);
console.log(resp);
} catch(e) {
alert(e);
}
}
希望这也适用于你
如果您正在处理来自AJAX(或XMLHttpRequest)调用的响应,对我来说有效的方法是检查响应内容类型,并相应地解析或不解析内容。
这个答案降低了trycatch语句的代价。
我使用JQuery来解析JSON字符串,我使用trycatch语句来处理异常,但是对于不可解析的字符串抛出异常会降低我的代码,所以我使用简单的Regex来检查字符串,如果它是一个可能的JSON字符串,或者不是通过检查它的语法来羽毛,然后我使用常规的方式通过JQuery解析字符串:
if (typeof jsonData == 'string') {
if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
return jsonData;
}
}
try {
jsonData = $.parseJSON(jsonData);
} catch (e) {
}
我将前面的代码包装在递归函数中,以解析嵌套的JSON响应。