isJsonString('{ "Id": 1, "Name": "Coke" }')

应该是正确的

isJsonString('foo')
isJsonString('<div>foo</div>')

应该为假。

我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。


当前回答

我知道我问这个问题已经晚了3年,但我还是想插话。

虽然Gumbo的解决方案工作得很好,但它不能处理一些没有引发JSON异常的情况。解析({非JSON})

我也更喜欢同时返回解析后的JSON,这样调用代码就不必再次调用JSON.parse(jsonString)。

这似乎很适合我的需求:

/**
 * If you don't care about primitives and only objects then this function
 * is for you, otherwise look elsewhere.
 * This function will return `false` for any valid json primitive.
 * EG, 'true' -> false
 *     '123' -> false
 *     'null' -> false
 *     '"I'm a string"' -> false
 */
function tryParseJSONObject (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;
};

其他回答

你当然可以用try catch来检查它是否是一个有效的JSON

在Firfox Quantom 60

在函数中使用函数来测试JSON,并使用该输出来验证字符串。听一个例子。

    function myfunction(text){

       //function for validating json string
        function testJSON(text){
            try{
                if (typeof text!=="string"){
                    return false;
                }else{
                    JSON.parse(text);
                    return true;                            
                }
            }
            catch (error){
                return false;
            }
        }

  //content of your real function   
        if(testJSON(text)){
            console.log("json");
        }else{
            console.log("not json");
        }
    }

//use it as a normal function
        myfunction('{"name":"kasun","age":10}')

你可以使用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将抛出异常。

这个答案降低了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响应。

从原型框架字符串。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);
  }

这个版本可以用来传递一个字符串对象

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 }" ) )

保持简单

函数isValidJsonString(测试器) / /早期现有 If (/^\s*$|undefined/.test(tester) || !(/number|object|array|string|boolean/。测试(typeof测试仪))) { 返回错误; }; //通过try catch进行解析 返回true; };