diff --git a/index.js b/index.js index 590491e..da362f8 100644 --- a/index.js +++ b/index.js @@ -77,6 +77,7 @@ function createObject() { */ var isint = /^[0-9]+$/; +var isnumstr = /^['"][0-9]+['"]$/; function promote(parent, key) { if (parent[key].length == 0) return parent[key] = createObject(); @@ -92,6 +93,9 @@ function promote(parent, key) { function parse(parts, parent, key, val) { var part = parts.shift(); + + key = isnumstr.test(key) ? key.replace(/['"]/g, '') : key; + // end if (!part) { if (isArray(parent[key])) { @@ -311,15 +315,18 @@ function stringifyArray(arr, prefix) { function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) - , key; + , key, val; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; + val = obj[key]; + if ('' == key) continue; - if (null == obj[key]) { + if (null == val) { ret.push(encodeURIComponent(key) + '='); } else { - ret.push(stringify(obj[key], prefix + key = isint.test(key) ? "'" + key + "'" : key; + ret.push(stringify(val, prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } @@ -340,6 +347,7 @@ function stringifyObject(obj, prefix) { */ function set(obj, key, val) { + key = isnumstr.test(key) ? key.replace(/['"]/g, '') : key; var v = obj[key]; if (undefined === v) { obj[key] = val; diff --git a/test/parse.js b/test/parse.js index a06dcd8..32ed1a3 100644 --- a/test/parse.js +++ b/test/parse.js @@ -160,6 +160,13 @@ describe('qs.parse()', function(){ expect(q).to.eql({ a: ['2', '1'] }); }) + it('should support objects with numbers as keys', function(){ + expect(qs.parse("a['111']=1")).to.eql({ a: { '111': '1' }}); + expect(qs.parse("'123'=hello")).to.eql({ '123': 'hello' }); + expect(qs.parse("a['111'][b]=222")).to.eql({ a: { '111': { b: '222' }}}); + expect(qs.parse('a["111"][b]=222')).to.eql({ a: { '111': { b: '222' }}}); + }) + if ('undefined' == typeof window) { it('should not be possible to access Object prototype', function() { qs.parse('constructor[prototype][bad]=bad'); diff --git a/test/stringify.js b/test/stringify.js index 0d52250..17dce7d 100644 --- a/test/stringify.js +++ b/test/stringify.js @@ -54,7 +54,9 @@ var str_identities = { ], 'numbers': [ { str: 'limit[0]=1&limit[1]=2&limit[2]=3', obj: { limit: [1, 2, '3'] }}, - { str: 'limit=1', obj: { limit: 1 }} + { str: 'limit=1', obj: { limit: 1 }}, + { str: "a['111']=1", obj: { a: { '111': 1 } } }, + { str: "'123'=hello", obj: { '123': "hello" } } ], 'others': [ { str: 'at=' + encodeURIComponent(date), obj: { at: date } }