Skip to content

Commit

Permalink
[Fix] parse: properly account for strictNullHandling when `allowE…
Browse files Browse the repository at this point in the history
…mptyArrays`

Fixes #510
  • Loading branch information
ljharb committed Jul 8, 2024
1 parent 7ebf48b commit 1bf9f7a
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ var parseObject = function (chain, val, options, valuesParsed) {
var root = chain[i];

if (root === '[]' && options.parseArrays) {
obj = options.allowEmptyArrays && leaf === '' ? [] : [].concat(leaf);
obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null))
? []
: [].concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
Expand Down
9 changes: 9 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,15 @@ test('parse()', function (t) {
st.end();
});

t.test('allowEmptyArrays + strictNullHandling', function (st) {
st.deepEqual(
qs.parse('testEmptyArray[]', { strictNullHandling: true, allowEmptyArrays: true }),
{ testEmptyArray: [] }
);

st.end();
});

t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
t.deepEqual(
Expand Down
12 changes: 12 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,18 @@ test('stringify()', function (t) {
st.end();
});

t.test('allowEmptyArrays + strictNullHandling', function (st) {
st.equal(
qs.stringify(
{ testEmptyArray: [] },
{ strictNullHandling: true, allowEmptyArrays: true }
),
'testEmptyArray[]'
);

st.end();
});

t.test('stringifies an array value with one item vs multiple items', function (st) {
st.test('non-array item', function (s2t) {
s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c');
Expand Down

0 comments on commit 1bf9f7a

Please sign in to comment.