JSON.parse is giving an "undefined" object

richerlariviere picture richerlariviere · Feb 26, 2015 · Viewed 15.9k times · Source

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!

Answer

Marvin Emil Brach picture Marvin Emil Brach · Feb 26, 2015

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]));
}