ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.47k stars 730 forks source link

The parse method returns incorrect output when both strictNullHandling and allowEmptyArrays are set to true #510

Closed Ari-ZH closed 1 month ago

Ari-ZH commented 1 month ago

Here is the test code: when strictNullHandling and allowEmptyArrays are both set to true, the parse function does not correctly interpret the result of stringify.

import { expect, test } from 'vitest';
import qs from 'qs';

const beforeParams = {
  testEmptyArray: [],
};

// stringify result
const searchStr = 'testEmptyArray[]';

// expect parse result
const afterParams = {
  testEmptyArray: [],
};

test('stringify', () => {
  expect(
    qs.stringify(beforeParams, {
      strictNullHandling: true,
      allowEmptyArrays: true,
    }),
  ).toBe(searchStr);
});

test('parseSearchStr', () => {
  expect(
    qs.parse(searchStr, { strictNullHandling: true, allowEmptyArrays: true }),
  ).toStrictEqual(afterParams);
  //  expect { testEmptyArray:[] } but return { testEmptyArray:[null] }
});

Version: 6.12.2

Ari-ZH commented 1 month ago

I believe the issue arises here. https://github.com/ljharb/qs/blob/main/lib/parse.js#L129 leaf is null when strictNullHandling is true , so it return [null]

ljharb commented 1 month ago

Thanks, this is very helpful.