views:

5588

answers:

3

For this example, assume that I have a list of months in a form, each with a checkbox next to them. I'm looking for help on doing either of two things:

  1. Convert a query string (e.g. "January=on&March=on&September=on") or
  2. Convert an object map: [{ January: 'on' },{ March: 'on' },{ September: 'on' }]

to a single JSON object: { January: 'on', March: 'on', September: 'on' }

I realize that the first map is already JSON, but instead of the object array I'd like it to be a single JSON object. I can build the map with $('form').serializeArray(); and I can build the query string with $('form').serialize();.

The implementation of .serialize() in the jQuery API is simply:

serialize: function() {
 return jQuery.param(this.serializeArray());
},

which is why I could handle either the first or second answer.

The reason I'd like to do this is because I'm switching from PrototypeJS to jQuery, and in PrototypeJS this was as simple as:

Object.toJSON(Form.serializeElements($('myform'), true));

So, does anybody know of a JSON plug-in (I'd like to stick with ONLY jQuery) that could do this easily, or know of a simple method to achieve the result I'm looking for? Thanks!

A: 

You can traverse an object map using the $.each utility function.

$(function() {
    map = [{ January: 'on' },{ March: 'on' },{ September: 'on' }];
    $.each(map, function() {
       $.each(this, function(key, val) {alert(key + " = " + val);});;
    });
});

The first each gets you all array objects. With the second one you can get the key and value of your object.

kgiannakakis
I think this is a good start -- at least something I can work with. How about the situation where each object in the map can have the same name? It's not exactly a requirement, but I'd like to handle that case if it comes up in the future. The complexity seems to go up quite a bit with that. I'll take your example and start working on something though...
Cory Larson
+1  A: 
Cory Larson
A: 

I know you're trying to turn a query-string into a JSON object, but perhaps you might be interested in going directly from an html form to a JSON object (without having to specify really convoluted name attributes). If so, check out JSONForms: http://code.google.com/p/jsonf/

Disclaimer: I started the jsonforms project. It's still young, but personally I think it rocks!

Jeoff Wilks
That's cool, but doesn't solve the issue. I'm using ASP.NET, so with all of the name mangling done by having NamingContainers everywhere, your library won't create very friendly object property names.
Cory Larson