I tried to parse this string :
[{"ZoneId": "1", "0": "1", "ZoneX": "29", "1": "29", "ZoneY": "27", "2": "27", "ZoneWidth": "76", "3": "76", "ZoneHeight": "61", "4": "61", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"},
{"ZoneId": "2", "0": "2", "ZoneX": "382", "1": "382", "ZoneY": "226", "2": "226", "ZoneWidth": "-117", "3": "-117", "ZoneHeight": "98", "4": "98", "ZoneImage": "46", "5": "46", "ZonePointTo": "3", "6": "3"},
{"ZoneId": "3", "0": "3", "ZoneX": "108", "1": "108", "ZoneY": "74", "2": "74", "ZoneWidth": "363", "3": "363", "ZoneHeight": "83", "4": "83", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"}]
Using JSON.parse() on this string show me "undefined" in the console. According to this site, my json is valid. It comes from a json_encode given by a php function.
If it can help, the final goal is to loop through this json array. Thanks.
[EDIT]
I realized that my error was in fact a scope issue using literal functions. Yes, I'm a bit stupid sometimes. Thanks everybody for your help!
This is no String
, its a valid JSON which you can use in JavaScript:
var jsonData = [{"ZoneId": "1", "0": "1", "ZoneX": "29", "1": "29", "ZoneY": "27", "2": "27", "ZoneWidth": "76", "3": "76", "ZoneHeight": "61", "4": "61", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"},
{"ZoneId": "2", "0": "2", "ZoneX": "382", "1": "382", "ZoneY": "226", "2": "226", "ZoneWidth": "-117", "3": "-117", "ZoneHeight": "98", "4": "98", "ZoneImage": "46", "5": "46", "ZonePointTo": "3", "6": "3"},
{"ZoneId": "3", "0": "3", "ZoneX": "108", "1": "108", "ZoneY": "74", "2": "74", "ZoneWidth": "363", "3": "363", "ZoneHeight": "83", "4": "83", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"}];
for(index in jsonData) {
alert(JSON.stringify(jsonData[index]));
}
your string is not json object
but
it is an json array object (check out the square brackets).
so to get the value you must run it into "for" or "each" or ...
.each example below
pass the string to variable and then ;
var obj=[{"ZoneId": "1", "0": "1", "ZoneX": "29", "1": "29", "ZoneY": "27", "2": "27", "ZoneWidth": "76", "3": "76", "ZoneHeight": "61", "4": "61", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"},
{"ZoneId": "2", "0": "2", "ZoneX": "382", "1": "382", "ZoneY": "226", "2": "226", "ZoneWidth": "-117", "3": "-117", "ZoneHeight": "98", "4": "98", "ZoneImage": "46", "5": "46", "ZonePointTo": "3", "6": "3"},
{"ZoneId": "3", "0": "3", "ZoneX": "108", "1": "108", "ZoneY": "74", "2": "74", "ZoneWidth": "363", "3": "363", "ZoneHeight": "83", "4": "83", "ZoneImage": "46", "5": "46", "ZonePointTo": "2", "6": "2"}]
jQuery.each(obj, function(key,value) {
alert(value.ZoneId);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With