简体   繁体   中英

How do I convert this multi-dimentional associative array to json?

I have a loop that creates an associative array in js that I need to convert to json.

Javascript:

var guest = {};
var guests = {};

for(var i=0;i<2;i++){
  var name = GetName();
  var email = GetEmail();
  guest = { 'Email': email, 'Name': name };
  guests.push(guest);
}

End of the loop would give me, say:

{
 {'Email':"bob@zyz.com", 'Name':"Mr. Bob"},
 {'Email':"tom@zyz.com", 'Name':"Mr. Tom"}
}

How can I convert this to JSON? (OK with small jquery plugin)

I need to pass this json array to my MVC 3 controller:

[HttpPost]
public ActionResult AddGuests(List<SelectedGuest> guests){

}

public class SelectedGuest
{
    public string Email { get; set; }
    public string Name { get; set; }
}

Thanks for reading.

You need square brackets if you want to deal with arrays. In javascript there are really two artifacts: objects ( {} ) and arrays of objects ( [] ) and the distinction is really important:

var guest = { };
var guests = [ ];

for(var i = 0; i < 2; i++) {
    var name = GetName();
    var email = GetEmail();
    guest = { 'Email': email, 'Name': name };
    guests.push(guest);
}

Now that we have fixed your javascript let's use AJAX to send this guests array to the AddGuests controller action:

$.ajax({
    url: '/SomeController/AddGuests',
    data: JSON.stringify(guests),
    type: 'POST',
    contentType: 'application/json', // <-- Make sure to set the proper content type
    success: function(result) {
        // TODO: handle the results of the controller action
    }
});

The JSON.stringify method shown here is implemented in most modern browsers but for older browsers you might want to include the following script .

One last remark:

Never hardcode urls in javascript like this:

url: '/SomeController/AddGuests'

Always use Url helpers in ASP.NET MVC when dealing with urls, like this:

url: '@Url.Action("AddGuests", "SomeController")'

After your for loop call JSON.stringify();

var json = JSON.stringify(guests);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM