I'm new to javascript and just learning AJAX calls and parsing JSON objects so I know I'm just missing something obvious. I can retrieve the JSON string from my API but I cannot parse it correctly. I'm not sure if I'm sending a JSON object that cannot be parsed or just trying to read the fields in the wrong way. Thanks for taking the time to read this and your help is greatly appreciated I'm just at a loss for where to go next.
I can get the JSON string by this.responseText but when I try to access the field Title I only get undefiend. I'm trying to access it this way: this.responseText.title I've also tried: this.responseText[title] and this.responseText["title"]
"{\"Id\":220,\"Title\":\"Drawtober 19\",\"YearCreated\":0,\"DatePublished\":\"2018-12-14T03:27:05.51\"}"
is what I get from the AJAX call and my attempt to get the title:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let x = this.responseText;
let firstTest = JSON.parse(x[0]);
let secondTest = JSON.parse(x.Title);
}
};
xhttp.open("GET", "http://www.faithfulimagination.com/api/artwork/220", true);
xhttp.send();
}
I'm expecting to see "Drawtober 19" and all I get is 'undefined'
EDIT
The issue was originally in my API as Barmar pointed out. I was calling JsonConvert.SerializeObject and returning a string rather than returning just the object.
Calling JSON.parse(x) twice worked perfectly as did fixing my API and only having to call it once.
Thank you all for answering so quickly! It seems everyone picked up on my problem right away.
let obj = JSON.parse(x);and then you can doobj.Title.