I need to be able to parse a string in an object format or in a plain string format. what is the safest way to do this?
I tried JSON.parse(data) but it does not work in case that data is a plain string.
Thanks to you, this is how I solved the problem:
try {
dataObj = JSON.parse(data);
} catch (err) {
if (typeof data === "object") {
dataObj = data;
} else {
dataObj = {};
}
}
Create yourself a helper function and use that.
function parseValue(value) {
try
{
return JSON.parse(value);
}
catch (ex)
{
// JSON format was invalid
// handle errors is you need to
}
return value;
}
If you're brave enough you can also extend String.prototype so calling it would become really straight forward.
String.prototype.parseJSON = String.prototype.parseJSON || function() {
try
{
return JSON.parse(this);
}
catch (ex)
{
// JSON format was invalid
// handle errors is you need to
}
return this;
};
And then you'd simply call it this way:
// string in a variable
var s = "Some non-JSON string";
s.parseJSON();
// string literal
'{"b":true,"n":1}'.parseJSON();
Use try catch:
var result;
try {
result = JSON.parse(data);
} catch (err) {
if (typeof data == 'string') result = data;
else console.error(err);
}
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