Reputation: 1213
I have confusion over the functionality of JSON.parse.
I am writing code :
dynamicMsgObj = '"rest, no disc"';
var jsonObj = {};
var isJsonString = function isJsonString(str) {
try {
jsonObj = JSON.parse(str);
} catch (e) {
return false;
}
return true;
}(dynamicMsgObj);
console.log(isJsonString);// returns true
console.log(typeof jsonObj);//returns string
How is this happening?? In this way I can't determine if I am receiving string or object, which is my main objective. Please help
Upvotes: 2
Views: 1914
Reputation: 48415
That's because JSON.parse
is able to successfully parse that input, it will parse it as a string and a string is what the return result will be.
Check out the documentation and look at the examples. This one specifically:
JSON.parse('"foo"'); // "foo"
And in regards to achieving your objective, you have done that already:
if(isJsonString && typeof jsonObj == 'string')
// is string
else
// is something else
Upvotes: 5