js-url icon indicating copy to clipboard operation
js-url copied to clipboard

Issues parsing array arguments?

Open maxguru opened this issue 8 years ago • 2 comments

Not sure if people consider this an issues, however, arrays are apparently padded with nulls for missing values,

> JSON.stringify(url('?','?t[0]=x&t[1]=y'));
"{"t":["x","y"]}"
> JSON.stringify(url('?','?t[0]=x&t[2]=y'));
"{"t":["x",null,"y"]}"

Maybe the better option would be to return objects for sparse arrays, like so,

> JSON.stringify(url('?','?t[0]=x&t[1]=y'));
"{"t":["x","y"]}"
> JSON.stringify(url('?','?t[0]=x&t[2]=y'));
"{"0":"x","2":"y"}"

maxguru avatar Mar 06 '18 06:03 maxguru

I think this is a complaint against how sparse arrays are represented in JSON, and not an issue with this library.

// an ordinary sparse array
var sparse = [0,,2];
console.log(`%o`, sparse); // [0, empty, 2]
console.log(JSON.stringify(sparse)); // [0, null, 2]

Notice that passing a sparse array through JSON.stringify results in information loss. These three different arrays can only be represented by one JSON object:

var sparse = [0,,2];
var undef = [0, undefined, 2];
var nully = [0, null, 2];

[sparse, undef, nully].forEach(a => console.log(JSON.stringify(a)));
// [0, null, 2]
// [0, null, 2]
// [0, null, 2]

Adding https://github.com/websanova/js-url into the mix isn't the source uncertainty. Representing a sparse array in JSON is the source of uncertainty.

var got = url('?','?t[0]=0&t[2]=2');
console.log(`%o`, got);    // {t: ["0", empty, "2"]}
console.log(JSON.stringify(got)); // '{"t": ["0", null, "2"]}'

I think js-url does not need to return a special sparse-array-object when it finds one, because it already returns properly sparse arrays.

belden avatar Feb 13 '20 15:02 belden

Vote to close per above

belden avatar Feb 13 '20 15:02 belden