6

I am getting JSON back from a web service. When I use jQuery.parseJSON, for some reason it is null. This is an example of the JSON (got by using JSON.stringify(msg))

{"0":{"i":"1x 8351-3 & 2 x 8352-3","D":"Notes","V":"1x 8351-3 & 2 x 8352-3"},"1":{"i":"PC3","D":"Unit","V":"PC3"},"2":{"i":"PC3","D":"Unit","De":"Unit","V":"PC3"}}
var data = jQuery.parseJSON(msg);

data is null? Am I missing something? Thanks

4
  • Cannot reproduce: jsfiddle.net/5VVqg. Make sure the actual JSON you receive is valid: jsonlint.org. Commented May 28, 2012 at 14:05
  • when i load you page i get [object Object] in alert, is that suppose to happen? Commented May 28, 2012 at 14:07
  • That's the default string representation of an object. It should demonstrate that the result is not null. It could also be that the JSON is already parsed. How you are you getting the data? Commented May 28, 2012 at 14:09
  • Probably one of these questions stackoverflow.com/search?q=jquery+parseJSON+returns+null will help you. Commented May 28, 2012 at 14:14

1 Answer 1

7

If your JSON is like this (assuming you are fetching data from web sevice via getJSON)

 {"error":"Error KL005"}

Then you don't need to call the parseJSON. It is a well formed JSON object. You can simply parse thru it.

var response={"error":"Error KL005"};
alert(response.error);

Example : http://jsfiddle.net/6YHeB/2/

Use JsonLint to check whether your expressions are valid JSON.

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

7 Comments

var response={"error":"Error KL005"}; is not JSON nor a well formed JSON object. It's simply a JavaScript object.
@FelixKling : Showed in a variable to demonstrate how to access the properties (from my js fiddle example). Fixed it now
It's still confusing. The crucial part is that if OP uses getJSON, then the JSON is already parsed. But that has nothing to do with the structure of the JSON. If the response is not valid JSON, jQuery would not be able to parse it anyway.
@FelixKling: Yea. I mentioned that (assuming you are using getJSON to get data). OP provided the JSON result he has and it seems to be valid JSON. So we do not need to parse it again. That was my whole point as well.
I think you are confusing object literals with JSON. JSON is a data exchange format and by itself is just text. It has to be converted into the data structures of the language you are using, this means into JavaScript objcts/arrays here. Valid JSON does not mean it does not have to be parsed, it means it is "parse-able". Methods such as $.getJSON or setting the dataType: 'json' option for $.ajax do this automatically for you.
|

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.