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

应该是正确的

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

应该为假。

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


当前回答

我从开头的注释推断,用例描述的是响应是HTML还是JSON。在这种情况下,当您确实收到JSON时,您可能应该解析它并在代码中的某个位置处理无效JSON。除此之外,我想如果您的浏览器收到了JSON但无效的JSON,您会希望得到通知(用户也会通过代理收到一些有意义的错误消息)!

因此,为JSON执行完整的正则表达式是不必要的(根据我的经验,对于大多数用例来说,这是不必要的)。你可能会更好地使用下面的方法:

function (someString) {
  // test string is opened with curly brace or machine bracket
  if (someString.trim().search(/^(\[|\{){1}/) > -1) {
    try { // it is, so now let's see if its valid JSON
      var myJson = JSON.parse(someString);
      // yep, we're working with valid JSON
    } catch (e) {
      // nope, we got what we thought was JSON, it isn't; let's handle it.
    }
  } else {
    // nope, we're working with non-json, no need to parse it fully
  }
}

这应该节省你不得不异常处理有效的非json代码,同时照顾duff json。

其他回答

如果你有疑问,值是或不是json

  function isStringified(jsonValue) { // use this function to check
   try {
    console.log("need to parse");
    return JSON.parse(jsonValue);
   } catch (err) {
    console.log("not need to parse");

     return jsonValue; 
    }
  }

然后

  const json = isStringified(stringValue);

  if (typeof json == "object") {
      console.log("string is a valid json")
    }else{
      console.log("string is not a valid json")
    }

也许它会有用:

    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));

输出:

IE7:字符串、对象、字符串,字符串

铬:对象、对象、字符串,字符串

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

我知道我问这个问题已经晚了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。 如果你不介意使用它,请阅读下面的答案。 这里我们只是使用regexp检查JSON字符串,它在大多数情况下都可以工作,而不是所有情况。

看看https://github.com/douglascrockford/JSON-js/blob/master/json2.js的450行

有一个regexp检查有效的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

}

编辑:新版本的json2.js进行了比上面更高级的解析,但仍然基于regexp替换(来自@Mrchief的评论)