5

I have a string st returned from a web service. I convert the string to an object, how can I count the no. of arrays inside it? (for this case it's 2)

var st = "{[{"Name": "fake", "Address": "add"]},[{"Name": "fake", "Address": "add"}]}";  
var json = eval(st);  

json.length is always returning 1

whoan
  • 8,143
  • 4
  • 39
  • 48
coure2011
  • 40,286
  • 83
  • 216
  • 349

5 Answers5

17

@coure06 I`ve changed a little bit your JSON. Hope this will be usefull

var persons = {
    "person1" : {
        "Name": "Adam",
        "Address": "USA" 
    },
    "person2" : {
        "Name": "Jamie",
        "Address": "USA" 
    }
};
var count = 0;
//var count = persons.length;          // wont work
for ( property in persons )          // should return 2
{
   if(persons.hasOwnProperty(property))
   {
      count++;
   }
}

Live example at jsfiddle

Bakudan
  • 19,134
  • 9
  • 53
  • 73
  • 1
    should use hasOwnProperty: `for( var x in persons ) if(persons.hasOwnProperty(x)) count++;` – vsync Feb 25 '12 at 13:54
5

I'm surprised json.length is returning anything; that JSON string is invalid. The outermost curly braces ({}) denote an object, which must contain keys and values, but it just contains a value (the array, with no key).

If you remove the curly braces, it should work correctly. Did you put them there, perhaps because you'd seen it done? If so, you want parentheses (()), not curly braces.

Note that using eval on JSON strings is not safe, you want to use a JSON decoder that doesn't use eval (like json2.js, which uses eval, but only after very carefully ensuring it's safe to do so, modifying it if necessary), for optimum safety. The parentheses help, but they're not at all a complete solution.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

Here's the trick!

var jsonString = "{field1:'data1',field2:'data2',arrField1:['arrField1Content1','arrField1Content2']}";
var obj = eval('(' + jsonString + ')');

var objCount=0;
for(_obj in obj) objCount++;

alert(objCount);
skidadon
  • 547
  • 4
  • 7
1

Try using this,

var persons = {
    "person1" : {
        "Name": "Adam",
        "Address": "USA" 
    },
    "person2" : {
        "Name": "Jamie",
        "Address": "USA" 
    }
};

Object.prototype.count = function() {
    var that = this,
        count = 0;

    for(property in that) {
        if(that.hasOwnProperty(property)) {
            count++;
        }
    }

    return count;
};

alert(persons.count());

this could work for nested objects like

var persons = {
    "person1" : {
        "Name": "Adam",
        "Address": "USA" 
    },
    "person2" : {
        "Name": "Jamie",
        "Address": "USA" ,
        "users": {
            "person1" : {
                "Name": "Adam",
                "Address": "USA" 
            },
            "person2" : {
                "Name": "Jamie",
                "Address": "USA" 
            }
        }
    }
};

alert(persons.person2.users.count());
Borderless.Nomad
  • 761
  • 1
  • 10
  • 23
-1
  1. That is not a valid JSON expression.
  2. There is no built-in way to count "members" of an object. You can write one, but it's problematic due to the squishy nature of the language.

edit — now that I've made it to the future, it's possible to use APIs like Object.keys(), Object.getOwnPropertyNames(), and Object.getOwnPropertySymbols to get a count of properties in an object:

var props = Object.getOwnPropertySymbols(someObject);
var length = props.length; // number of properties

In my experience, it's pretty rare that I've cared about the number of properties in an object; usually, if you don't know what an object is already, you're interested in specific properties (by name). However there's nothing wrong with using those APIs.

Pointy
  • 405,095
  • 59
  • 585
  • 614