2

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

Is JS typecasting object into string after parsing? But why " 'foo' " doesn't work this way? How is " 'foo' " a simple string but ' "foo" ' is a json string?
The difference is that "foo" is valid JSON, whereas 'foo' is not. Unlike javascript, JSON does not allow " and ' to be interchangeable. What may be your confusion, and that of many, is that JSON is just a method of representing (or serializing) a javascript data object as a string. And strings are just javascript data objects like any other
Thanks musefan. I didn't know the JSON method's behaviour.
No problem, I hope you are able to implement a solution with your new understanding ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.