views:

182

answers:

2

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 its 2)

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

json.length is always returning 1

A: 
  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.
Pointy
+2  A: 

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