简体   繁体   中英

JSON.parse parsing a string into string

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM