Skip to content

Instantly share code, notes, and snippets.

@bigeasy
Created March 31, 2009 14:19
Show Gist options
  • Save bigeasy/88211 to your computer and use it in GitHub Desktop.
Save bigeasy/88211 to your computer and use it in GitHub Desktop.
jQuery Plugin to Convert text/plain Name Value Key Pairs to a Hash
(function ($) {
// Keep a copy of the old get.
var jQuery_get = jQuery.get;
jQuery.extend({
get: function( url, data, callback, type, options ) {
// Shift arguments if data argument was omitted.
if ( jQuery.isFunction( data ) ) {
type = callback;
callback = data;
data = null;
}
var actualCallback = callback;
var actualType = type;
if ( type != null && type == "hash" ) {
actualType = "text";
actualCallback = function ( text ) {
text = text.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' );
var parameters = text.split( /\n/ );
var hash = {};
for ( var i = 0 ; i < parameters.length ; i++ ) {
var pair = parameters[ i ].split( /=/ );
var name = unescape( pair[ 0 ] ).toLowerCase();
var value = pair.length == 1 ? "" : unescape( pair[ 1 ] );
var parts = name.split( /\./ );
for ( var j = 0 ; j < parts.length - 1 ; j++ ) {
if ( hash[ parts[ j ] ] == null ) hash[ parts[ j ] ] = {};
hash = hash[ parts[ j ] ];
}
hash[ parts[ parts.length - 1 ] ] = value;
}
var populate = function( hash, paths, builder ) {
for ( var i = 0 ; i < paths.length ; i ++ ) {
var parts = paths[ i ].split( /\./ );
for ( var j = 0; j < parts.length - 1; j ++ ) {
if ( hash[ parts[ j ] ] == null ) hash[ parts[ j ] ] = {};
hash = hash[ parts[ j ] ];
}
if ( hash[ parts[ parts.length - 1 ] ] == null )
hash[ parts[ parts.length - 1 ] ] = {};
}
}
if ( !options ) options = {};
if ( options[ 'hashes' ] ) populate( hash, options[ 'hashes' ], function () { return new Object() } );
if ( options[ 'arrays' ] ) populate( hash, options[ 'arrays' ], function () { return new Array() } );
callback( hash );
}
}
jQuery_get( url, data, actualCallback, actualType );
}
});
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment