Q:

doing .length on json array returns undefined

I have following json encoded array coming from ajax call 
{"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}}

Following is my ajax code
$.ajax({
   method: "POST",
   url: "test.php",
   data: "action=2",
   cache: 'false',
   success: function(abcd){
     alert(abcd);
     var obj = new Array();
     var obj = $.parseJSON(abcd);
     alert(obj.country.length);
   }
});

When i try using obj.country[0] it returns "United States of America". But when i try to get the length of the array using obj.country.length it returns undefined. 
I have browsed a couple of posts and only difference i could see was use of dataType: json and using header() to define content type to json on .php page. I have tried both methods but that didn't work out either. And on .php page i have declared following as array:
$data = array();
$data['country'] = array();
$data['country']['United States of America'] = array();
$data['country']['United States of America']['states'] = array();
$data['country']['United States of America']['states']['Alaska']['cities'] = array();

A:

This is because obj.country isn't an array, but an object.
An object is enclosed in curly braces ({}) and an array in square ones ([]). See http://json.org/ for more information.
In your example content, "cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"] would be an array, which you can call with obj["country"]["United States of America"]["states"]["Alaska"]["cities"].

So, judging from your example this would work:
$us['name'] = "United";
$alaska['name'] = "Alaska";
$alaska['cities'] = array("city1", "city2");
$us['states'] = array($alaska)
$data = array($us);

I expect it would render like [{"name": "United", "states": [{"name":"Alaska", "cities": ["city1","city2"]}]}].
I'm sure it could be done better or more compact though, I don't have much experience with PHP in this regard.

