Skip to content

Commit

Permalink
[Fix] ensure key[]=x&key[]&key[]=y results in 3, not 2, values.
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Jul 20, 2016
1 parent 657b340 commit 5ac31b4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 16 deletions.
23 changes: 10 additions & 13 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,18 @@ var parseValues = function parseValues(str, options) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;

var key, val;
if (pos === -1) {
obj[options.decoder(part)] = '';

if (options.strictNullHandling) {
obj[options.decoder(part)] = null;
}
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
var key = options.decoder(part.slice(0, pos));
var val = options.decoder(part.slice(pos + 1));

if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}

Expand Down
31 changes: 28 additions & 3 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,34 @@ test('parse()', function (t) {

t.test('allows for empty strings in arrays', function (st) {
st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
st.deepEqual(qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true }), { a: ['b', null, 'c', ''] });
st.deepEqual(qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true }), { a: ['b', '', 'c', null] });
st.deepEqual(qs.parse('a[]=&a[]=b&a[]=c'), { a: ['', 'b', 'c'] });

st.deepEqual(
qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }),
{ a: ['b', null, 'c', ''] },
'with arrayLimit 20 + array indices: null then empty string works'
);
st.deepEqual(
qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }),
{ a: ['b', null, 'c', ''] },
'with arrayLimit 0 + array brackets: null then empty string works'
);

st.deepEqual(
qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }),
{ a: ['b', '', 'c', null] },
'with arrayLimit 20 + array indices: empty string then null works'
);
st.deepEqual(
qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }),
{ a: ['b', '', 'c', null] },
'with arrayLimit 0 + array brackets: empty string then null works'
);

st.deepEqual(
qs.parse('a[]=&a[]=b&a[]=c'),
{ a: ['', 'b', 'c'] },
'array brackets: empty strings work'
);
st.end();
});

Expand Down

0 comments on commit 5ac31b4

Please sign in to comment.