如何在不使用 Try/Catch 的情况下检查字符串是否为 JavaScript 中的有效 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3710204/
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
How to check if a string is a valid JSON string in JavaScript without using Try/Catch
提问by Chi Chan
Something like:
就像是:
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.
解决方案不应包含 try/catch。我们中的一些人打开“中断所有错误”,他们不喜欢调试器中断那些无效的 JSON 字符串。
采纳答案by Mic
A comment first. The question was about not using try/catch.
If you do not mind to use it, read the answer below.
Here we just check a JSONstring using a regexp, and it will work in most cases, not all cases.
先评论一下。问题是关于不使用try/catch.
如果您不介意使用它,请阅读下面的答案。这里我们只是JSON使用正则表达式检查字符串,它在大多数情况下都有效,而不是所有情况。
Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js
看看https://github.com/douglascrockford/JSON-js/blob/master/json2.js 中的第 450 行
There is a regexp that check for a valid JSON, something like:
有一个检查有效 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
}
EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief)
回答by Gumbo
Use a JSON parser like JSON.parse:
使用 JSON 解析器,如JSON.parse:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
回答by Matt H.
I know i'm 3 years late to this question, but I felt like chiming in.
我知道我问这个问题晚了 3 年,但我想插话。
While Gumbo's solution works great, it doesn't handle a few cases where no exception is raised for JSON.parse({something that isn't JSON})
虽然 Gumbo 的解决方案效果很好,但它不能处理一些没有引发异常的情况 JSON.parse({something that isn't JSON})
I also prefer to return the parsed JSON at the same time, so the calling code doesn't have to call JSON.parse(jsonString)a second time.
我也更喜欢同时返回解析后的 JSON,这样调用代码就不必JSON.parse(jsonString)第二次调用了。
This seems to work well for my needs:
这似乎很适合我的需求:
function tryParseJSON (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;
};
回答by moeiscool
// vanillaJS
function isJSON(str) {
try {
return (JSON.parse(str) && !!str);
} catch (e) {
return false;
}
}
Usage:isJSON({})will be false, isJSON('{}')will be true.
用法:isJSON({})将是false,isJSON('{}')将是true。
To check if something is an Arrayor Object(parsedJSON):
要检查某个东西是否是Array或Object(解析的JSON):
// vanillaJS
function isAO(val) {
return val instanceof Array || val instanceof Object ? true : false;
}
// ES2015
var isAO = (val) => val instanceof Array || val instanceof Object ? true : false;
Usage:isAO({})will be true, isAO('{}')will be false.
用法:isAO({})将是true,isAO('{}')将是false。
回答by Anand Kumar
Here my working code:
这是我的工作代码:
function IsJsonString(str) {
try {
var json = JSON.parse(str);
return (typeof json === 'object');
} catch (e) {
return false;
}
}
回答by kukko
I used a really simple method to check a string how it's a valid JSON or not.
我使用了一种非常简单的方法来检查字符串是否是有效的 JSON。
function testJSON(text){
if (typeof text!=="string"){
return false;
}
try{
JSON.parse(text);
return true;
}
catch (error){
return false;
}
}
Result with a valid JSON string:
具有有效 JSON 字符串的结果:
var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;
Result with a simple string;
结果是一个简单的字符串;
var input='This is not a JSON string.';
testJSON(input); // returns false;
Result with an object:
结果与对象:
var input={};
testJSON(input); // returns false;
Result with null input:
结果为空输入:
var input=null;
testJSON(input); // returns false;
The last one returns false because the type of null variables is object.
最后一个返回false,因为空变量的类型是对象。
This works everytime. :)
这每次都有效。:)
回答by Ifi
回答by loretoparisi
From Prototype framework String.isJSONdefinition here
从这里的原型框架String.isJSON定义
/**
* String#isJSON() -> Boolean
*
* Check if the string is valid JSON by the use of regular expressions.
* This security method is called internally.
*
* ##### Examples
*
* "something".isJSON();
* // -> false
* "\"something\"".isJSON();
* // -> true
* "{ foo: 42 }".isJSON();
* // -> false
* "{ \"foo\": 42 }".isJSON();
* // -> true
**/
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
so this is the version that can be used passing a string object
所以这是可以用于传递字符串对象的版本
function isJSON(str) {
if ( /^\s*$/.test(str) ) return false;
str = str.replace(/\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
function isJSON(str) {
if ( /^\s*$/.test(str) ) return false;
str = str.replace(/\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
console.log ("this is a json", isJSON( "{ \"key\" : 1, \"key2@e\" : \"val\"}" ) )
console.log("this is not a json", isJSON( "{ \"key\" : 1, \"key2@e\" : pippo }" ) )
回答by Rabih
This answer to reduce the cost of trycatch statement.
这个答案降低了 trycatch 语句的成本。
I used JQuery to parse JSON strings and I used trycatch statement to handle exceptions, but throwing exceptions for un-parsable strings slowed down my code, so I used simple Regex to check the string if it is a possible JSON string or not without going feather by checking it's syntax, then I used the regular way by parsing the string using JQuery :
我使用 JQuery 来解析 JSON 字符串,并使用 trycatch 语句来处理异常,但是为不可解析的字符串抛出异常会减慢我的代码速度,所以我使用简单的 Regex 来检查字符串是否是可能的 JSON 字符串,而不会出现问题通过检查它的语法,然后我通过使用 JQuery 解析字符串来使用常规方法:
if (typeof jsonData == 'string') {
if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
return jsonData;
}
}
try {
jsonData = $.parseJSON(jsonData);
} catch (e) {
}
I wrapped the previous code in a recursive function to parse nested JSON responses.
我将前面的代码包装在一个递归函数中来解析嵌套的 JSON 响应。
回答by Rabih
Maybe it will useful:
也许它会有用:
function parseJson(code)
{
try {
return JSON.parse(code);
} catch (e) {
return code;
}
}
function parseJsonJQ(code)
{
try {
return $.parseJSON(code);
} catch (e) {
return code;
}
}
var str = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
alert(typeof parseJson(str));
alert(typeof parseJsonJQ(str));
var str_b = "c";
alert(typeof parseJson(str_b));
alert(typeof parseJsonJQ(str_b));
output:
输出:
IE7: string,object,string,string
IE7:字符串,对象,字符串,字符串
CHROME: object,object,string,string
铬:对象,对象,字符串,字符串

