Nov
9
2011

Element to JSON

Wouldn’t it be neat to simply take all fields from a form or any other element for that matter and create a JSON object?

Well with this simple block of code below now you can do something like:

console.log($('myElement').toJSON());

And there you have it a nice neat JSON Object!

The MooTools Code:

Element.implement({
	toJSON: function(){
		var j = {};
		Array.each(this.toQueryString().split('&'),function(i){
			var a = i.split('=')
			j[a[0]] = a[1]||'';
		});
		return JSON.encode(j);
	}
});

Simply add that after you include mooTools core on your page, or better yet add it to your utilities file that you take with you to every project!

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.