Alexander Zakusilo Alexander Zakusilo - 2 months ago 8
JSON Question

How to convert JSON deep object to URL params in JavaScript?

I want to convert deep JSON to URL params string. I have json:

{ filter: { dir: 184}, b:'a'}


and

{ filter: [1,2,3], b:'a'}


So I want the result string like this:

filter[dir]=188&b=a
filter[]=1&filter[]=2&filter[]=3&b=a


How to do this in JavaScript (not Jquery)?

Answer

You could use an iterative and recursive style for the values.

function getString(o) {

    function iter(o, path) {
        if (Array.isArray(o)) {
            o.forEach(function (a) {
                iter(a, path + '[]');
            });
            return;
        }
        if (o !== null && typeof o === 'object') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], path + '[' + k + ']');
            });
            return;
        }
        data.push(path + '=' + o);
    }

    var data = [];
    Object.keys(o).forEach(function (k) {
        iter(o[k], k);
    });
    return data.join('&');
}

var data1 = { filter: { dir: 184 }, b: 'a' },
    data2 = { filter: [1, 2, 3], b: 'a' },
    data3 = { filter: [1, 2, 3], b: 'a', c: { d: { e: 42 } } };

console.log(getString(data1));
console.log(getString(data2));
console.log(getString(data3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments