Серожа (ckayt) wrote,
Серожа
ckayt

working with query string in javascript (php-style parsing and serializing)

function a2qs(a,pfx){
    var pfx = typeof(pfx) == 'string' ? pfx : '';
    var ts;
    var sa = [];
    for(k in a){
        var tk = encodeURIComponent(k);
        if(typeof(a[k])=='object'){
            sa[sa.length] = a2qs(a[k],(pfx?pfx+'['+tk+']':tk));
        }else
            sa[sa.length] = (pfx?pfx+'['+tk+']':tk)+'='+encodeURIComponent(a[k]);
    };
    return sa.join('&');
};

function qs2a(qs){
    var qa = qs.split('&');
    var ta = {};
    var a = {};
    var tk = [];
    var i;
    for(i in qa){
        qa[i] = qa[i].split('=', 2);
        if(typeof(qa[i][1]) == 'undefined')
            qa[i][1] = '';
    };

    var next = function(a){
        var na = [];
        var i;
        if(typeof(a) == 'object')
        for(i in a)
        if(!/[^0-9]/.test(i))
            na[na.length] = parseInt(i,10);
        na[na.length] = -1;
        return Math.max.apply(Math, na)+1;
    };

    var pool = {};
    var uk;


    for(i in qa){
        var uk = qa[i][0];
        var uv = qa[i][1];

        var suk = uk.replace(/^([^\[]*)(\[([^\]]*)\])/, '$1!!$3');

        if(suk != uk){
            suk = suk.split('!!', 2);
            uk = suk[0] ? suk[0] : next(a);
            if(typeof(pool[uk]) == 'undefined')
                var tp = pool[uk] = [];
            tp[tp.length] = suk[1]+'='+uv;
        }else
            a[uk ? decodeURIComponent(uk) : next(a)] = decodeURIComponent(uv);

    };

    for(uk in pool){
        var tp = pool[uk];
        a[decodeURIComponent(uk)] = qs2a(pool[uk].join('&'));
    };

    return a;
};


// example 1
var qs1 = 'a[a]=aa&a[b]=ab&b[c]=bc&c=c';
var qa = qs2a(qs1);
var qs2 = a2qs(qa);

document.write(qs1 + '<br />');
document.write(qs2 + '<br />');

document.write('<hr />');

// example 2
var qs1 = 'a[]=a&a[]=b&a[]=c&a[1][50]=lolo&a[1][gg]=ggs&a[1][]=pepe';
var qa = qs2a(qs1);
var qs2 = a2qs(qa);

document.write(qs1 + '<br />');
document.write(qs2 + '<br />');
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 1 comment