Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using try/catch to verify JSON? [duplicate]

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

should be true and

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

should be false.

I'm looking for a solution that doesn't use try/catch because I have my debugger set to "break on all errors" and that causes it to break on invalid JSON strings.

like image 613
Chi Chan Avatar asked Aug 10 '26 14:08

Chi Chan


1 Answers

Here's a function that uses JSON.parse to return a bool indicating whether the JSON string can be successfully parsed:

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

Here's a similar function that will either return the parsed object, or null if it couldn't be parsed.

function parse_json(json_string)
{
    let json_object = null;
    
    try
    {
        json_object = JSON.parse(json_string);
    }
    
    catch (e)
    {
        return null;
    }
    
    return json_object;
}
like image 63
Gumbo Avatar answered Aug 13 '26 03:08

Gumbo