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

应该是正确的

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

应该为假。

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


当前回答

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

其他回答

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

下面是typescript版本:

JSONTryParse(input: any) {
    try {
        //check if the string exists
        if (input) {
            var o = JSON.parse(input);

            //validate the result too
            if (o && o.constructor === Object) {
                return o;
            }
        }
    }
    catch (e: any) {
    }

    return false;
};

我使用了一个非常简单的方法来检查字符串是否为有效的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。

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

下面是我的工作代码:

function IsJsonString(str) {
  try {
    var json = JSON.parse(str);
    return (typeof json === 'object');
  } catch (e) {
    return false;
  }
}
if(resp) {
    try {
        resp = $.parseJSON(resp);
        console.log(resp);
    } catch(e) {
        alert(e);
    }
}

希望这也适用于你