+ 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.

29th Aug 2017, 10:49 AM
Stoyan Todorov
Stoyan Todorov - avatar
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
29th Aug 2017, 6:38 PM
Burey
Burey - avatar
+ 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
29th Aug 2017, 6:58 PM
Burey
Burey - avatar
+ 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.
29th Aug 2017, 7:11 PM
Stoyan Todorov
Stoyan Todorov - avatar
+ 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
29th Aug 2017, 12:45 PM
Stoyan Todorov
Stoyan Todorov - avatar
+ 4
Thank you! I suspected that asynchronous call had something to do with this issue. But I'm still a noob in JS
29th Aug 2017, 6:46 PM
Stoyan Todorov
Stoyan Todorov - avatar
+ 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
29th Aug 2017, 12:34 PM
Paul