如何检查字符串是否是有效的JSON字符串?

52 浏览
0 Comments

如何检查字符串是否是有效的JSON字符串?

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

应该为 true

isJsonString('foo')
isJsonString('foo')

应该为 false

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

admin 更改状态以发布 2023年5月21日
0
0 Comments

我知道我回答这个问题已经晚了3年,但我还想说几句。

虽然Gumbo的解决方案很好用,但它无法处理一些情况,比如JSON.parse({something that isn't 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;
};

0
0 Comments

使用类似JSON.parse的JSON解析器:

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

0