我想将深度JSON转换为URL params字符串。我有json:
filter[dir]=188&b=a
filter[]=1&filter[]=2&filter[]=3&b=a
和
{{1}}
所以我想要这样的结果字符串:
{{1}}
如何在JavaScript(而不是Jquery)中执行此操作?
答案 0 :(得分:1)
您可以对值使用迭代和递归样式。
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; }

答案 1 :(得分:0)
function build(input) {
var output = "";
// Loop each property in the base object.
for (var p in input) {
var item = input[p];
// Need to handle differently for Array, Object, and OTHER.
if (item instanceof Array) {
// Loop each array value and append to output.
for (var x in item) {
output += "&" + p + "[]=" + item[x];
}
} else if (item instanceof Object) {
// Loop each sub object property and append to output.
// NOTE: We assume only a single level of object depth, this is NOT a recursive solution.
for (var x in item) {
output += "&" + p + "[" + x + "]=" + item[x];
}
} else {
// Any other object type is just appended to output as is.
output += "&" + p + "=" + item;
}
}
// Finally, if we have any output, trim the first leading '&' character.
if (output.length > 0)
output = output.substring(1);
return output;
}
console.log(build({ filter: { dir: 184}, b:'a'}));
console.log(build({ filter: [1,2,3], b:'a'}));

.as-console-wrapper { max-height: 100% !important; top: 0; }