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

应该是正确的

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

应该为假。

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


当前回答

var jsonstring='[{“ConnectionString”:“aaaaa”,“Server”:“ssssss”}]'; if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){ document.write(“valide json”) }else{ document.write(“invalide json”) }

其他回答

下面是我的工作代码:

function IsJsonString(str) {
  try {
    var json = JSON.parse(str);
    return (typeof json === 'object');
  } 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}')

在prototypeJS中,我们有方法isJSON。你可以试试。甚至json也可能有所帮助。

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
// -> true

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

var jsonstring='[{“ConnectionString”:“aaaaa”,“Server”:“ssssss”}]'; if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){ document.write(“valide json”) }else{ document.write(“invalide json”) }