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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With