0

So having an absolute nightmare reading a JSON reply Whatever I do I get either a list of object Object, undefined or other issue, but I can not get the actual information out of the JSON reply, but there is a JSON reply. What am I missing. The JSON call looks like this

var mapKeyUrl = "/GenMap/getcountry/jsonchk";
var mapKeyUrl = "/GenMap/getcountry/jsonchk"
$.getJSON(mapKeyUrl, {
    regsel: "${regsel}",
    countryiso: code
})
.done(function( contdata ) {
    alert(contdata)
    contdata = contdata.country
    alert(contdata)
    document.getElementById("maptext").innerHTML = "I am an abwrock " + code + contdata.exturl;
})

The response (as taken from the chrome debug) looks as follows

{"country":
    [
     {"ccode":["EG"]},
     {"cname":["Egypt"]},
     {"exturl":["N/A"]},
     {"impdate":[null]},
     {"lupdate":["2014-09-28T23:00:00Z"]},
     {"impnote":[null]}
    ]
}
vrghost
  • 1,084
  • 2
  • 19
  • 42

3 Answers3

2

You have an array in there that you are not accounting for. You would need to access your data as follows:

console.log(contdata); // would dump entire object
console.log(contdata.country); // would dump inner array with length of 1
console.log(contdata.country[0]); // would dump object inside array
console.log(contdata.country[0].ccode[0]); // would dump country code
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Eventually got it with contdata.country[0].cname[0]. Certain the other solutions works as well, but this one suited me the best. – vrghost Oct 09 '14 at 16:36
1

Whatever generated this seems to have over complicated matters and wrapped it several times.

What you need to do is find the object with the property you want (the key) then pull the value, which is actually a value in an array itself.

What I'd do is something like:

var getProp = function(countryData, name) {
   for(var i = 0; i < countryData.length; i++) {
       if (countryData[i].hasOwnProperty(name)) {
           var value_array = countryData[i][name];

           return value_array[0];
       }
   }

   return null;
};

var code = getProp(contdata,"ccode");
var ext_url = getProp(contdata,"exturl");
Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • Sorry, code is defined outside (should have mentioned). How do I access an object within the contdata array that is called exturl. – vrghost Oct 09 '14 at 16:23
1

Try this:

    alert(JSON.stringify(contdata));

OR Use

   console.log(contdata);

OR Use

   console.dir(contdata);
Nitish Kumar
  • 4,850
  • 3
  • 20
  • 38