+ 5
I need help with JSON.parse()
I get a syntax error when trying to parse Jon string. here's the code https://code.sololearn.com/WtdeKxFN43YJ/?ref=app Thank you in advance.
6 Respuestas
+ 12
switch
if(http.status>=200 && http.status<400)
with
if(http.readyState === XMLHttpRequest.DONE && http.status === 200)
your JSON.parse occurs before the request is done, causing an invalid JSON
+ 12
in case you were wondering, what happens is this:
right after clicking the button the http.status is 200 which means the request was succesful, however the json response has not returned yet
and the http.responseText now contains an empty string, which obviously is not null
therefore it passes the if condition and the JSON.parse tries to parse an empty string
JSON.parse("") which results in the error you have gotten
+ 5
in C# (from where I get my programing experience ) when there's an asynchronous method there's an await keyword preventing this. I've decided to play safe placing an if statement to check for null but I didn't know that in JS strings are always initialized.
+ 4
My api response value is a valid JSON string but JS cannot parse it for some reason. I've validated it manually and hardcoded it - yet still I get the syntax erorr
+ 4
Thank you! I suspected that asynchronous call had something to do with this issue. But I'm still a noob in JS
+ 1
at what format do you receive that json? Parse works on strings if i am not mistaken. you could tru to do smething like "toString"(can't look up to this cause I do not know JS). if you convert the response to a string I think it should work, otherwise try to load it to a JObject variable instead of parsing it