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

应该是正确的

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

应该为假。

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


当前回答

我使用了一个非常简单的方法来检查字符串是否为有效的JSON。

function testJSON(text){
    if (typeof text!=="string"){
        return false;
    }
    try{
        var json = JSON.parse(text);
        return (typeof json === 'object');
    }
    catch (error){
        return false;
    }
}

返回一个有效的JSON字符串:

var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;

返回一个简单的字符串;

var input='This is not a JSON string.';
testJSON(input); // returns false;

返回一个对象:

var input={};
testJSON(input); // returns false;

输入为空的结果:

var input=null;
testJSON(input); // returns false;

最后一个返回false,因为空变量的类型是object。

这种方法每次都有效。:)

其他回答

isValidJsonString - check for valid json string JSON data types - string, number, object (JSON object), array, boolean, null (https://www.json.org/json-en.html) falsy values in javascript - false, 0, -0, 0n, ", null, undefined, NaN - (https://developer.mozilla.org/en-US/docs/Glossary/Falsy) JSON.parse works well for number , boolean, null and valid json String won't raise any error. please refer example below JSON.parse(2) // 2 JSON.parse(null) // null JSON.parse(true) // true JSON.parse('{"name":"jhamman"}') // {name: "jhamman"} JSON.parse('[1,2,3]') // [1, 2, 3] break when you parse undefined , object, array etc it gave Uncaught SyntaxError: Unexpected end of JSON input . please refer example below JSON.parse({}) JSON.parse([]) JSON.parse(undefined) JSON.parse("jack")

function isValidJsonString(jsonString){
    
    if(!(jsonString && typeof jsonString === "string")){
        return false;
    }

    try{
       JSON.parse(jsonString);
       return true;
    }catch(error){
        return false;
    }

}

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

如果你有疑问,值是或不是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")
    }

先评论一下。问题是关于不使用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的评论)

保持简单

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