AJAX:检查字符串是否是JSON?

Nic*_*ner 82 javascript validation ajax json

我的JavaScript有时会崩溃在这一行:

var json = eval('(' + this.responseText + ')');
Run Code Online (Sandbox Code Playgroud)

当参数eval()不是JSON 时会导致崩溃.在进行此调用之前,有没有办法检查字符串是否为JSON?

我不想使用框架 - 是否有任何方法可以使用这个工作eval()?(我保证,有充分的理由.)

ink*_*dmn 155

如果您从json.org 包含JSON解析器,您可以使用它的parse()函数并将其包装在try/catch中,如下所示:

try
{
   var json = JSON.parse(this.responseText);
}
catch(e)
{
   alert('invalid json');
}
Run Code Online (Sandbox Code Playgroud)

像这样的东西可能会做你想要的.

  • 使用jQuery.parseJSON(..)你不需要包含json.org (9认同)

Ray*_*ess 21

她的jQuery替代品......

try
{
  var jsonObject = jQuery.parseJSON(yourJsonString);
}
catch(e)
{
  // handle error 
}
Run Code Online (Sandbox Code Playgroud)


Håv*_*d S 14

我强烈建议您使用javascript JSON库来串行化JSON.eval()是一种安全风险,除非您绝对确定其输入已经过消毒且安全,否则不应使用.

使用JSON库,只需将调用包装parse()在try/catch-block中,以处理非JSON输入:

try
{
  var jsonObject = JSON.parse(yourJsonString);
}
catch(e)
{
  // handle error 
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*UMI 8

Promise而不是Try-catch:

npm install is-json-promise ; //for NodeJS environment.
Run Code Online (Sandbox Code Playgroud)

要么

String.IsJSON = (candidate) => 
   new Promise(
     (resolve, reject) => resolve(JSON.parse(candidate))
    ) 
;
Run Code Online (Sandbox Code Playgroud)

用例 :

String.IsJSON(`iam here`)
   .then((object) => console.info(object))
   .catch((error) => alert('Waww, i cannot be JSON')) ; // promise will run catch
Run Code Online (Sandbox Code Playgroud)

要么

String.IsJSON(`{"welcome":"Hello"}`)
   .then((object) => console.info(object)) // promise will run "then"
   .catch((error) => alert('Waww, i cannot be JSON')) ; 
Run Code Online (Sandbox Code Playgroud)