views:

329

answers:

2

I'm creating a JsonArray such as:

JsonArray jsonValues = new JsonArray();
 for( int i = 0; i < values.Count; i++ )
 {
   var someSingleValue = values[i];
    jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
 }

After that I'm shipping json values to my javascript in .aspx page via call: HtmlPage.Window.Invoke("call", jsonValues);

The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them. I've tried: (in javascript)

for (var x in somevalues){ alert(somevalues); }

I also tried:

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

but it crashes.(in both cases) any ideas?

A: 

Assuming somevalues is truly an array, you do it like this:

for(var i = 0; i < somevalues.length; i++) {
   // do something with somevalues[i]
}

What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.


EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.

Jason Bunting
I've tried that and I get an error: object doesn't support this property or method
ra170
yes, it was a string.
ra170
+1  A: 

Are you using the eval method to serialize the string to a JSON object?

function call(somevalues){

  //somevalues is currently just a string.
  var results = eval("(" + somevalues +")");

  //results now should contain your array as a JSON object.    

  //and you should be able to iterate over it at this point.
  for(var i = 0; i < results.length; i++){
     alert(results[i]);
  }
}
sgriffinusa
I've tried using eval before, however I made a mistake and didn't use parenthesis "(" + ")". Thanks!
ra170
Honestly, you shouldn't use eval, you should use a safe JSON parser to turn JSON into a JavaScript object. Google for them, they exist and provide you protections that eval() will not.
Jason Bunting
Good tip about not using eval with untrusted input. I found a project on Google Code that will do it and compares itself to a couple of apparently more common JSON parsers available from json.orghttp://code.google.com/p/json-sans-eval/
sgriffinusa