websanova / js-url

url() - A simple, lightweight url parser for JavaScript
http://www.websanova.com
MIT License
1.93k stars 204 forks source link

Issues parsing array arguments? #66

Open maxguru opened 6 years ago

maxguru commented 6 years ago

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"}"
belden commented 4 years ago

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 commented 4 years ago

Vote to close per above