Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Have you tested this in multiple browsers and still receive the same 'undefined' string? –  James Feb 7 '12 at 8:46

3 Answers 3

up vote 2 down vote accepted

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"
share|improve this answer

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.

share|improve this answer
    
This doesn't help getting the response value, are the escape codes stopping me from reading it. This doesn't work: data.contents.response –  danielbeard Feb 7 '12 at 8:38
    
@danielbeard I hadn't seen that. My goodness me that's a ridiculous API. –  lonesomeday Feb 7 '12 at 9:24

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.