Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

json array

Status
Not open for further replies.

KryptoS

Programmer
Feb 7, 2001
240
BE
Hello,

I'm really stuck on this. So if anyone can help me...

With php I'm passing a value back to an Ajax request.
Something like this:
{"field1":{"isEmpty":"this field can not be empty"},"field2":{"isEmpty":"this field can not be empty"}}

I can get the value in my javascript like this:

msg = Ext.decode(response.responseText);
alert(msg.field1.isEmpty);
alert(msg.field2.isEmpty);

But I don't want it to be an object. Can I make it an array? Because the number of fields are not always the same. With an array I can loop through the messages and show the alerts.

I hope it's a little bit clear...

The One And Only KryptoS
 
With an array I can loop through the messages and show the alerts.

You can do the same with an object, though, so why convert it to an array if you don't need to?

Code:
var myObj = {
   field1: {
      isEmpty: 'this field can not be empty'
   },
   field2: {
      isEmpty: 'this field can be empty'
   }
}

var s = '';
for (props in myObj) {
   s += 'myObj[' + props + '] = ' + myObj[props] + '\n';
}

alert(s);

If the properties are objects, you can just recursively call the routine to iterate properties of these objects.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
thanks. To make it complete, I did this:

Code:
for (props in msgObj) {
  for(props1 in msgObj[props]) {
    s += '- ' +props+ ': ' +msgObj[props][props1] + '<br>';
  }
}
alert(s)

So I get an alert with:
field1: This field can not be empty
field2: This field can not be empty

The One And Only KryptoS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top