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

应该是正确的

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

应该为假。

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


当前回答

如果您正在处理来自AJAX(或XMLHttpRequest)调用的响应,对我来说有效的方法是检查响应内容类型,并相应地解析或不解析内容。

其他回答

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

}

使用JSON.parse这样的JSON解析器:

function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

如果你不想在任何地方执行try/catch,寻找一个单一的行程序,并且不介意使用异步函数:

const isJsonString = async str => ( await ((async v => JSON.parse(v))(str)).then(_ => true).catch(_ => false) );

await isJsonString('{ "Id": 1, "Name": "Coke" }'); // true
await isJsonString('foo'); // false
await isJsonString('<div>foo</div>'); // false

也许它会有用:

    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:字符串、对象、字符串,字符串

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

下面是我的工作代码:

function IsJsonString(str) {
  try {
    var json = JSON.parse(str);
    return (typeof json === 'object');
  } catch (e) {
    return false;
  }
}