0

I am using JQuery's getJSON() to request JSON from my web server. Then, I want to parse the response. The format of the JSON response is as follows:

{
    "responseStatus": "200",
    "responseData": {
        "resultText": "Hello"
    },
    "originalText": "hi"
}

And my JQuery code:

$.getJSON(url, function (json) {
     $.each(json, function (i, result) {
         alert(result.resultText);
     });
});

The problem I am facing is that I receive three alert windows in a row: "Undefined", "Hello", and "Undefined". I am only looking to get and show the single value for resultText. Why am I also receiving the "Undefined"?

Thanks!

5 Answers 5

2

I think you can do:

$.getJSON(url,function(json){

   alert(json.responseData.resultText);       

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

1 Comment

That did the trick, thanks! I'm new to JQuery, so I'm still trying to learn all of the syntax.
2

When you iterate through the json object, you will first have the object "responseStatus". If you try to do responseStatus.resultText it is undefined as responseStatus does not have that property. The same goes for "originalText"

In order to see the single result just use:

$.getJSON(url, function (json) {
    alert(json.responseData.resultText);
});

Comments

2

try this one (you can do it directly)

$.getJSON(url,function(json){
         alert(json.responseData.resultText);
});

Comments

2

You're iterating the entire response...meaning you're hitting

  1. responseStatus
  2. responseData
  3. originalText

However, only your responseData property has a resultText property.

Comments

2

responseData is just a plain object why are you using $.each loop just try

$.getJSON(url,function(json){
    alert(json.responseData.resultText);       
});

You are getting three alerts because you are looping through whole json object which has 3 properties

$.getJSON(url, function (json) {
     $.each(json, function (i, result) {
         //In this loop result will point to each of the properties
         //of json object and only responseData has resultText property 
         //so you will get proper alert other wise for other properties
         //it is undefined. 
         alert(result.resultText);
     });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.