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.
EDIT - The chosen solution
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 = {};
}
}
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.
EDIT - The chosen solution
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 = {};
}
}
Share
Improve this question
edited Jul 20, 2015 at 17:12
Robert Koritnik
105k56 gold badges286 silver badges413 bronze badges
asked Jul 19, 2015 at 13:16
RavitRavit
1,5423 gold badges19 silver badges25 bronze badges
2
-
If
data
can be an object, why don't you test that before you are trying to parse it? That would make more sense. Also, if it can be an object, why don't you mention that in your question? You said the value would be a string. – Felix Kling Commented Jul 19, 2015 at 22:40 - After I wrote the question I found more edge cases. – Ravit Commented Jul 20, 2015 at 7:02
3 Answers
Reset to default 3Create 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 bee 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);
}
Assuming the JSON will always have the same format, you could also check whether the string starts with a {"
(or just {
), and only then parse it with JSON.parse
.
It really depends of the possible input though.