Created
March 2, 2012 16:11
-
-
Save trydionel/1959381 to your computer and use it in GitHub Desktop.
$.serializeJSON()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Rails-style JSON serialization. e.g., Given a form: | |
// | |
// <input type="text" name="foo[bar][]" value="qux" /> | |
// <input type="text" name="foo[bar][]" value="quux" /> | |
// | |
// $("form").serializeJSON() will serialize to | |
// | |
// { foo: { bar: [ "qux", "quux" ] } } | |
// | |
$.fn.serializeJSON = function() { | |
var json = {}, | |
tokenize = function(input) { | |
return input.split('[') | |
.map(function(t) { | |
return t.replace(']', ''); | |
}); | |
}, | |
baseObject = function(json, tokens, depth) { | |
var out = json; | |
for (var i = 0; i < depth; i++) | |
out = out[tokens[i]]; | |
return out; | |
}; | |
jQuery.map($(this).serializeArray(), function(n, i) { | |
var name = n['name'], | |
tokens = tokenize(name), | |
value = n['value']; | |
for (var i = tokens.length - 1; i > -1; i--) { | |
var token = tokens[i], tmp = {}; | |
// If the token is blank, we're dealing with an array. | |
// Handle this by wrapping the single value in an array | |
// and attaching it to the next token up if it's an array, | |
// or just creating a new array if not. | |
// | |
if (token == "") { | |
if ((base = baseObject(json, tokens, i)) && $.isArray(base)) { | |
base.push(value); | |
i = 0; // We've updated the final output, so just break out of loop | |
} else { | |
tmp = [value]; | |
} | |
} else { | |
tmp[token] = value; | |
} | |
value = tmp; | |
} | |
$.extend(true, json, value); | |
}); | |
return json; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment