user1023465 user1023465 - 4 months ago 7
JSON Question

How do I access an element of this JSON object created by JSON.parse?

I am using an AJAX POST to send a JSON object from the client side my server. However, I'm a little confused as to how to access the object once it gets there.

Here's my POST from the client side:



var data = JSON.stringify({
'app': 'reviews',
'name': '',
'review': '',
'response': '',
'rating': rating,
'url': url,
'date': date
});
console.log(data);
$.ajax({
type: "POST",
url: "https://stormy-plateau-94715.herokuapp.com/",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data['success']);
},
failure: function(errMsg) {
alert(errMsg);
}
});





This works just fine. On my server, I print the body of the request and it looks fine:

"{\"app\":\"reviews\",\"name\":\"\",\"review\":\"\",\"response\":\"\",\"rating\":4.5,\"url\":\"test.com\",\"date\":\"7/5/2016\"}"


Then I call JSON.parse on it, and everything still works as I expected, here is the result:

{"app":"reviews","name":"","review":"","response":"","rating":4.5,"url":"test.com","date":"7/5/2016"}

This is saved in a variable called post. However, when I try to access post.app or post['app'], I get an undefined. Can anybody let me know where I'm going wrong?

Answer

This very same issue happened to me when I mistakenly used JSON.stringify on an object that was already a string, which it looks is exactly what you are doing.

Comments