1

I have following json

[{\"Country\":\"Europe\",\"City\":[\"Berlin\",\"Istanbul\",\"London\",\"Manchester\",\"Milan\",\"Paris\"]},null]

I want to read the country and its cities.

I have tried it like this

var eu = jQuery.parseJSON($("#EU").val());
        for( i=0; i<eu.length();i++)
        {
          alert( eu[0][0]);
          }

But I am getting undefined error in alert.

How can I accomplish the above task?

3
  • please show your HTML too... your problem might be in your selector. You'll also have a problem with alert( eu[0][0]); anyway as you might want to include i somewhere here... Commented Dec 8, 2014 at 10:18
  • I guess eu[0] is object and you can call [0] for it. It should be eu[0]["Country"] or eu[0]["City"]. I think you want eu[0]["City"][0] Commented Dec 8, 2014 at 10:19
  • Can you check what $("#EU").val() and jQuery.parseJSON($("#EU").val()) are returning? Commented Dec 8, 2014 at 10:21

4 Answers 4

1

length is a property and not a method. Just drop the ():

for( i=0; i<eu.length;i++) {
  alert( eu[i].Country );
}

Furthermore, you have an Array of objects, so eu[0][0] does not exists. To output the country, eg., use eu[0].Country or eu[0]['Country'].

Besides, your second Array element is null, so you should check for that (or receive an error):

for( i=0; i<eu.length;i++) {
  if( 'Country' in eu[i] ) {
    alert( eu[i].Country );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

still giving undefined
@abc Then probably the way you retrieve the JSON is wrong. Please add the respective HTML for #EU.
1

You can try this within the for loop :

for( i=0; i<eu.length;i++)
{
  alert( eu[0]['Country']);
  alert( eu[0]['City'][0]);
 }

Comments

0

if #EU is an form input it will get the json, if its a div or html element try text() to get the json

$("#EU").text();

and the fix the loop

for( var i=0, x = eu.length; i < x; i++) //length 

Comments

0

You can use below code which is much simpler.

var vJson = [{"Country":"Europe","City":["Berlin","Istanbul","London","Manchester","Milan","Paris"]}];

$.each(vJson, function(idx, obj) { 
    alert(obj.Country); // Get Country
    $.each(obj.City, function(idx1, obj1) { 
        alert(obj1); // Get multiple city of country
    });
});

Comments