From eecd28d292aa4c89d112ac769f2807c062deebcb Mon Sep 17 00:00:00 2001 From: Alexander Yefanov Date: Sun, 15 Mar 2020 10:45:46 +0100 Subject: [PATCH] [Fix] `parse`: Fix parsing array from object with `comma` true Fixes #357 --- lib/parse.js | 14 ++++++++++---- test/parse.js | 6 ++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/parse.js b/lib/parse.js index 8db3a5f8..3be8e1bc 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -29,6 +29,14 @@ var interpretNumericEntities = function (str) { }); }; +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } + + return val; +}; + // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset @@ -84,9 +92,7 @@ var parseValues = function parseQueryStringValues(str, options) { val = interpretNumericEntities(val); } - if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { - val = val.split(','); - } + val = parseArrayValue(val, options); if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; @@ -103,7 +109,7 @@ var parseValues = function parseQueryStringValues(str, options) { }; var parseObject = function (chain, val, options) { - var leaf = val; + var leaf = parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; diff --git a/test/parse.js b/test/parse.js index fcfd86ac..903b2af3 100644 --- a/test/parse.js +++ b/test/parse.js @@ -400,6 +400,12 @@ test('parse()', function (t) { st.end(); }); + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { var decoder = function (str, defaultDecoder, charset, type) { if (!isNaN(Number(str))) {