Reputation: 9149
I am trying to parse a JSON response from a server using javascript/jquery. This is the string:
{
"status": {
"http_code": 200
},
"contents": "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nDate: Tue, 07 Feb 2012 08:14:38 GMT\r\nServer: localhost\r\n\r\n {\"response\": \"true\"} "
}
I need to get the response
value.
Here is what I am trying in the success function of my POST query:
success: function(data) {
var objstring = JSON.stringify(data);
var result = jQuery.parseJSON(JSON.stringify(data));
alert(objstring);
var result1 = jQuery.parseJSON(JSON.stringify(result.contents[0]));
alert(result1.response);
alert(data.contents[0].response);
But so far nothing I have tried returns the correct result' I keep getting undefined
, however the contents of objstring
are correct and contain the JSON string.
Upvotes: 0
Views: 1538
Reputation: 272386
Seems like the JSON response itself contains JSON content. Depending on how you call the jQuery.post()
method, you'll either get a string or a JSON object. For the first case, use jQuery.parseJSON() to convert the string to a JSON object:
data = jQuery.parseJSON(theAboveMentionedJsonAsString);
Next, get everything inside the contents
property after the first \r\n\r\n
:
var contentBody = data.contents.split("\r\n\r\n", 2)[1];
Lastly, convert that string to JSON and get the desired value:
var response = jQuery.parseJSON(contentBody).response;
// "true"
Upvotes: 2
Reputation: 1215
try it this way:
var objstring=JSON.stringify(data);
var result=JSON.parse(objstring);
alert("http code:" + result.status.http_code);
alert("contents:" + result.contents);
Upvotes: 0
Reputation: 238075
First, set dataType
to json
. Then data
will be an object containing the data specified:
dataType: 'json',
success: function(data) {
alert(data.status.http_code);
alert(data.contents);
}
Read the API for more explanation of what these properties achieve. It would also probably help you to use a Javascript console, so you can use console.log
, a much more powerful tool than alert
.
Upvotes: 4