Javascript AJAX:检查字符串是否为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2313630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AJAX: Check if a string is JSON?
提问by Nick Heiner
My JavaScript sometimes crashes on this line:
我的 JavaScript 有时会在这一行崩溃:
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?
当 of 的参数eval()不是 JSON时会导致崩溃。在进行此调用之前,有什么方法可以检查字符串是否为 JSON?
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.)
我不想使用框架 - 有什么方法可以让这个工作只使用eval()?(有一个很好的理由,我保证。)
回答by inkedmn
If you include the JSON parserfrom json.org, you can use it's parse() function and just wrap it in a try/catch, like so:
如果您包含来自 json.org的JSON 解析器,您可以使用它的 parse() 函数并将其包装在 try/catch 中,如下所示:
try
{
var json = JSON.parse(this.responseText);
}
catch(e)
{
alert('invalid json');
}
Something like that would probably do what you want.
这样的事情可能会做你想做的。
回答by RayLoveless
Hers's the jQuery alternative...
她的 jQuery 替代品......
try
{
var jsonObject = jQuery.parseJSON(yourJsonString);
}
catch(e)
{
// handle error
}
回答by H?vard S
I highly recommend you use a javascript JSON libraryfor serializing to and from JSON. eval()is a security risk which should never be used unless you are absolutely certainthat its input is sanitized and safe.
我强烈建议您使用javascript JSON 库来进行JSON序列化。eval()是一种安全风险,除非您绝对确定其输入是经过消毒和安全的,否则永远不应使用。
With a JSON library in place, just wrap the call to its parse()equivalent in a try/catch-block to handle non-JSON input:
有了 JSON 库,只需将调用包装parse()在 try/catch 块中以处理非 JSON 输入:
try
{
var jsonObject = JSON.parse(yourJsonString);
}
catch(e)
{
// handle error
}
回答by Abdennour TOUMI
Promiseinstead of Try-catch:
Promise而不是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')) ;
回答by Dujardin Emmanuel
Maybe this helps: With this code, you can get directly your data…
也许这会有所帮助:使用此代码,您可以直接获取数据……
<!DOCTYPE html>
<html>
<body>
<h3>Open console, please, to view result!</h3>
<p id="demo"></p>
<script>
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": "<p>Ceci est un texte en fran?ais !</p>","en-GB": "<p>And here, a text in english!</p>","nl-NL": "","es-ES": ""}';
tryJSON(test);
</script>
</body>
</html>
回答by Ramazan Polat
There is a tiny library that checks JavaScript types: is.js
有一个检查 JavaScript 类型的小库:is.js
is.json({foo: 'bar'});
=> true
// functions are returning as false
is.json(toString);
=> false
is.not.json([]);
=> true
is.all.json({}, 1);
=> false
is.any.json({}, 2);
=> true
// 'all' and 'any' interfaces can also take array parameter
is.all.json([{}, {foo: 'bar'}]);
=> true
Actually is.jsis much more then this, some honorable mentions:
var obj = document.createElement('div');
is.domNode(obj);
=> true
is.error(new Error());
=> true
is.function(toString);
=> true
is.chrome();
=> true if current browser is chrome
回答by ADM-IT
回答by Hesham Yassin
The problem with depending on the try-catchapproach is that JSON.parse('123') = 123and it will not throw an exception. Therefore, In addition to the try-catch, we need to check the type as follows:
依赖于try-catch方法的问题在于JSON.parse('123') = 123它不会抛出异常。因此,除了try-catch,我们还需要检查类型如下:
function isJsonStr(str) {
var parsedStr = str;
try {
parsedStr = JSON.parse(str);
} catch (e) {
return false;
}
return typeof parsedStr == 'object'
}
回答by Musa Kurt
Below is a function, you can try:
下面是一个函数,你可以试试:
String.prototype.isJson = function () {
try {
JSON.parse(this.toString());
return true;
} catch (ex) {
return false;
}
};

