Having an issue with my JSON as it throws me an undefined error. What's puzzling is that it recognizes my first variable without any problem.
Below are the codes for better understanding:
JSON
{"Comics":[
{"comic" :
{
"src":"Pictures/Comics/dw.jpg",
"descr":"Doctor Who has a nice tv show."
}
},
{"comic" :
{
"src":"Pictures/Comics/spi.jpg",
"descr":"Spider man is a nice comic \
The main spider-man comic \
ended with Peter Parker's \
death."
}
},
{"comic" :
{
"src":"Pictures/Comics/gg.jpg",
"descr":"Power puff girls also has a \
nice tv show . \
You should try watching it."
}
},
{"comic" :
{
"src":"Pictures/Comics/v.jpg",
"descr":"V fo Vendeta is a nice \
graphical volume written by\
Allan Moor who also wrote \
Watchmen. Those books had a movie."
}
}
]
}
Javascript Code
var arrI = new Array(4);
var arrD = new Array(4);
var x = new XMLHttpRequest;
x.onload = function(){
if(x.status == 200){
var txt = JSON.parse(x.responseText);
for(var g = 0; g<txt.Comics.length; g++){
arrI[g] = txt.Comics[g].comic.src;
arrD[g] = txt.Comics[g].comic.descr;
alert(arrD[g]);
}
}
}
x.open("GET",'Ajax/ImgCom.json', true);
x.send(null);
The strange part is that the
arrI[g] = txt.Comics[g].comic.src;
is working fine. It alerts the src
correctly. However, the issue arises with the desc
variable which results in giving me undefined
. Even though both have correct paths, I can't understand why this discrepancy exists.
I attempted to rectify using https://jsonlint.com, which showed me the following error:
Error: Parse error on line 5:
....jpg", "descr": 'Doctor Who has a ni
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Desperate for a solution, I even tried changing the "
of the desc field to '
, but unfortunately, it didn't resolve the problem.
Furthermore, experimenting with the ...=txt.Comics[g].comic[desc]
notation also didn't result in getting rid of the undefined value.
I thoroughly reviewed for any typos, but couldn't find any. Perhaps there might be some hidden mistakes causing this issue.
Appreciate your time and assistance in advance.