I get a JSON file via jQuery $.getJSON(url, function(data) { ... and want to parse it with either

var obj = JSON.parse(data);

or

var obj = jQuery.parseJSON(data);

alert(obj.center);

The first line gives me "syntax error" (using IE8, should support JSON.parse), the second gives me "'center' is null or not an object".

This is the valid JSON file I'm using:

{
"center":{"lat":"51.99637","lon":"13.07520"},
"locations":
[
    { "name":"a string","info":"another string" },
    ... some more here ...
]
}

I'm not too familiar with Javascript. What am I doing wrong?

If I use a simple JSON array (= just the content of locations) I get valid data with $.each. Do I have to do something with data before I can use JSON.parse on it?

Thanks!

share|improve this question

3 Answers

up vote 4 down vote accepted

The problem is that the name of the function is slightly misleading : it doesn't give you JSON but already a parsed object. What it does is fetch some JSON and parse it for you.

data is a plain javascript object, you don't need to parse it.

share|improve this answer
Should probably be JSON.parseFromString – Explosion Pills 18 hours ago
I'd suggest to rename the function as $.fetchSomeJSONAndParseItForMePlease = $.getJSON; – dystroy 18 hours ago
Considering how angry people seem to get when someone calls a JavaScript object "JSON," you'd think more people would be up in arms about changing the jQuery method name to $.getJavaScriptDataStructure – Explosion Pills 18 hours ago
Yeah, let's make a manifesto web site stop-confusing-people-about-what-is-json-with-your-stupid-function-name.org ! – dystroy 18 hours ago
Ah, cool, works. Thanks for this quick answer! Should have been obvious to me. Sorry for not thinking. – bolero 18 hours ago

$.getJSON will parse the data for you - you don't need to parse it manually after the fact.

share|improve this answer

You could try something like

var object = {}
object.text = "Hello World!"

var json = JSON.stringify(object)
alert(json)

var object = JSON && JSON.parse(json) || $.parseJSON(json)
alert(object.text)

Jsfiddle link

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.