0

JSON.parse throws error when I try to parse a valid JSON object. My issue is i'm receiving data from webservice and sometimes it works with parse and sometimes it doesn't not sure what is the reason why. I would expect JSON.parse to return same object if its a valid JSON object? or parse it if its a string.

 var obj1= { Result: Inprogress };
 var json = JSON.parse(obj1);

please help me with this understanding

13
  • 1
    There is no such thing as a "JSON object". JSON is a string. Commented Sep 21, 2015 at 16:08
  • 1
    @Stumblor yes, Tomalak is correct. JSON is a serialization scheme. The OP here is talking about a JavaScript object, not a JSON object. Commented Sep 21, 2015 at 16:11
  • 1
    @Stumblor Point #1: Don't link to w3schools as a reference source. They are not credible and should not be used. The JSON reference source is json.org. Point #2: JSON always is a string. If you think differently, you are making the same mistake as the OP. Commented Sep 21, 2015 at 16:12
  • @Tomalak perhaps you could provide an alternative reference then, so that we don't continue making the mistake? Commented Sep 21, 2015 at 16:14
  • 1
    But ofcourse JSON object exists, that having methods parse and stringify ... Btw. @Stumblor Even in the w3schools article you've linked they say : "... but the JSON format is text only ..." Commented Sep 21, 2015 at 16:20

2 Answers 2

2

What you have there is a JavaScript object. It doesn't need to be parsed because it's plain JavaScript syntax and JavaScript itself parses it. JSON is a serialization format.

The JSON.parse() method takes a string argument, like one retrieved from an ajax call or from local storage or some other source of data that only deals in string values.

Sign up to request clarification or add additional context in comments.

4 Comments

but why JSON.parse throws error...? we can't parse javascript object to JSON?
@DanFisher If you want to convert a JavaScript object to a JSON string, use JSON.stringify(). The verb "to parse" describes the process of interpreting text (contents of a string), so "parse to JSON" is backwards and doesn't make sense.
I understand that my question is i'm receiving the object/string from someone else and i'm not sure about which one it is. I get error sometimes and I don't get error sometimes. I want to know why JSON.parse gives error when its a valid object!!!
@DanFisher well, if it really is a valid blob of JSON syntax, then you won't get an error. The JSON parser is pretty strict.
0

Your JSON is malformed. A right JSON is

{ "Result": "Inprogress" }

You have forgotten the "" character in beginning and in end of each part of your JSON.

Comments

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.