0

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.

1
  • Have you tested this in multiple browsers and still receive the same 'undefined' string? Commented Feb 7, 2012 at 8:46

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 I hadn't seen that. My goodness me that's a ridiculous API.
2

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"

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.