What I'm trying to do: I'm trying to parse a list of json objects. I made a REST API that returns a list of JSON objects, formatted like this:
[{"_id":"61d7aca1ae700aeb4f9f9470","username":"test","email":"[email protected]","hasConfirmedEmail":false,"password":"test1234","createdAt":"2022-01-07T02:59:45.408Z","updatedAt":"2022-01-07T02:59:45.408Z","__v":0,"type":"user"}]
and I want to get the username of the first one. How would I do this in Javascript & JQuery?
What I'm doing: I've tried doing:
jQuery.ajax({
url: 'localhost:3000/my/api/route',
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function(data) {
// using err to visualize the data temporarily
err.innerHTML = json.parse(data)[0].username
},
error: function(req, status, thrown) {
err.innerHTML = thrown
},
timeout: 120000,
});
but that just returns: [object, Object]
What am I doing wrong?
CodePudding user response:
Because the object is in an array indicated by the square brackets on each end you can access the first item by using the index 0, then get the username from the object.
data[0].username
