if is ajax,AJAX: Check if a string is JSON?

可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

问题:

My JavaScript sometimes crashes on this line:

var json = eval('(' + this.responseText + ')');

Crashes are caused when the argument of eval() is not JSON. Is there any way to check if the string is JSON before making this call?

I don't want to use a framework - is there any way to make this work using just eval()? (There's a good reason, I promise.)

回答1:

If you include the JSON parser from json.org, you can use it's parse() function and just wrap it in a try/catch, like so:

try

{

var json = JSON.parse(this.responseText);

}

catch(e)

{

alert('invalid json');

}

Something like that would probably do what you want.

回答2:

Hers's the jQuery alternative...

try

{

var jsonObject = jQuery.parseJSON(yourJsonString);

}

catch(e)

{

// handle error

}

回答3:

I highly recommend you use a javascript JSON library for serializing to and from JSON. eval() is a security risk which should never be used unless you are absolutely certain that its input is sanitized and safe.

With a JSON library in place, just wrap the call to its parse() equivalent in a try/catch-block to handle non-JSON input:

try

{

var jsonObject = JSON.parse(yourJsonString);

}

catch(e)

{

// handle error

}

回答4:

Promise instead of Try-catch:

npm install is-json-promise ; //for NodeJS environment.

OR

String.IsJSON = (candidate) =>

new Promise(

(resolve, reject) => resolve(JSON.parse(candidate))

)

;

Use cases :

String.IsJSON(`iam here`)

.then((object) => console.info(object))

.catch((error) => alert('Waww, i cannot be JSON')) ; // promise will run catch

or

String.IsJSON(`{"welcome":"Hello"}`)

.then((object) => console.info(object)) // promise will run "then"

.catch((error) => alert('Waww, i cannot be JSON')) ;

回答5:

The problem with depending on the try-catch approach is that JSON.parse('123') = 123 and it will not throw an exception. Therefore, In addition to the try-catch, we need to check the type as follows:

function isJsonStr(str) {

var parsedStr = str;

try {

parsedStr = JSON.parse(str);

} catch (e) {

return false;

}

return typeof parsedStr == 'object'

}

回答6:

Below is a function, you can try:

String.prototype.isJson = function () {

try {

JSON.parse(this.toString());

return true;

} catch (ex) {

return false;

}

};

回答7:

Maybe this helps:

With this code, you can get directly your data…

Open console, please, to view result!

var tryJSON = function (test) {

try {

JSON.parse(test);

}

catch(err) {

// maybe you need to escape this… (or not)

test = '"'+test.replace(/\\?"/g,'\\"')+'"';

}

eval('test = '+test);

console.debug('Try json:', test);

};

// test with string…

var test = 'bonjour "mister"';

tryJSON(test);

// test with JSON…

var test = '{"fr-FR": "

Ceci est un texte en français !

","en-GB": "

And here, a text in english!

","nl-NL": "","es-ES": ""}';

tryJSON(test);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值