I’m trying to parse some JSON coming from an AJAX request using jQuery.
Basically, the JSON is encoded by PHP and looks like:
{"1":{"key1":"value1","key2":"value2"},"0":{"key1":"value1","key2":"value2"}}
The callback function of $.ajax looks like:
$.each(data, function(item) {
console.log($.type(item));
myfunction(item.key1);
});
item is recognized as a string and item.key1 is undefined.
The content-type of the response is “application/json” so jQuery is supposed to parse it. data is then recognized as an object.
So… what’s wrong?
The
itemis aString.The first argument of the callback of
$.each()is the key. In your example, your JSON object is anObjectwith numerical indexes, except in strings. You are attempting to access the property from the property name. Instead, you’d want to usedata[item]in your example.You want to access the property values like so…
Variables names have been changed to be clearer.
In a real
Array, the arguments would be be the index followed by the value.