Question

I've got a .each loop that is processing an object returned from a JSON feed a la Ajax (Type: jsonp; success function sends the "data" to the function/method that contains the .each loop).

What's got me scratching my head is that, if the feed returns more than one set of data, it parses it out just fine. But if the feed returns only ONE set of data, the loop is trying to break out the individual fields of that lone record, as if each field were a record itself.

Here are examples of the object that comes in from the Ajax routine:

Example 1: -- single item

{
  "SmeDetail": {
    "SipAddress": "jane.smith@whatever.com",
    "SubjectExpert": "Smith,Jane",
    "SubjectMatter": "Unix"
  }
}

Example 2: -- multiple items

{
  "SmeDetail": [
    {
      "SipAddress": "fred.flintstone@whatever.com",
      "SubjectExpert": "Flintstone,Fred",
      "SubjectMatter": "Bedrock"
    },
    {
      "SipAddress": "barney.rubble@whatever.com",
      "SubjectExpert": "Rubble,Barney",
      "SubjectMatter": "Bedrock"
    },
    {
      "SipAddress": "wilma.flintstone@whatever.com",
      "SubjectExpert": "Flintsone,Wilma",
      "SubjectMatter": "Bedrock"
    }
  ]
}

Now, here's the .each routine:

$.each(json_data.SmeDetail, function (i,val){
  var sip_address = val.SipAddress;
  var SME_name = val.SubjectExpert;
  var subject_matter = val.SubjectMatter;
  var sip_link = "<a href='sip:" + sip_address +
      "'><img src='http://server/prod/images/im.gif' hspace='2' border='0'  title='Send an instant message to " + 
      SME_name + "' alt='Send an instant message to " + 
      SME_name + "'/></a>";
  output7 = output7 + "<tr><td>" + 
      SME_name + " " + sip_link + "</td></tr>";
});

I put some alert statements in there so I could verify the data. And when this runs for a single record coming back from the feed, it loops three times and assigns "undefined" to all of the variables. So, because it's looping exactly three times, plus the fact that it's entering the loop at all, tells me it sees a "SmeDetail" record, but it's treating each individual field as a record.

Makes me wonder if the structure of that return of a single record is correct? Should there be brackets around that lone item?

Was it helpful?

Solution

var detail = json_data.SmeDetail;
if (!detail.length) detail = [detail];
$.each(detail,....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top