diff --git a/README.md b/README.md index 1a5481ac5..59d62c2c1 100644 --- a/README.md +++ b/README.md @@ -538,6 +538,7 @@ The first argument can be either a `url` or an `options` object. The only requir body streams are not allowed. * `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above. * `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON. +* `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body. * `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request. * `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request. * `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise. diff --git a/request.js b/request.js index 93239feb7..39c338a0c 100644 --- a/request.js +++ b/request.js @@ -1308,7 +1308,7 @@ Request.prototype.onRequestResponse = function (response) { if (self._json) { try { - response.body = JSON.parse(response.body) + response.body = JSON.parse(response.body, self._jsonReviver) } catch (e) {} } debug('emitting complete', self.uri.href) @@ -1495,6 +1495,10 @@ Request.prototype.json = function (val) { } } + if (typeof self.jsonReviver === 'function') { + self._jsonReviver = self.jsonReviver + } + return self } Request.prototype.getHeader = function (name, headers) { diff --git a/tests/test-json-request.js b/tests/test-json-request.js index af41964bd..08a963a68 100644 --- a/tests/test-json-request.js +++ b/tests/test-json-request.js @@ -32,6 +32,26 @@ function testJSONValue(testId, value) { }) } +function testJSONValueReviver(testId, value, reviver, revivedValue) { + tape('test ' + testId, function(t) { + var testUrl = '/' + testId + s.on(testUrl, server.createPostJSONValidator(value, 'application/json')) + var opts = { + method: 'PUT', + uri: s.url + testUrl, + json: true, + jsonReviver: reviver, + body: value + } + request(opts, function (err, resp, body) { + t.equal(err, null) + t.equal(resp.statusCode, 200) + t.deepEqual(body, revivedValue) + t.end() + }) + }) +} + testJSONValue('jsonNull', null) testJSONValue('jsonTrue', true) testJSONValue('jsonFalse', false) @@ -48,6 +68,11 @@ testJSONValue('jsonObject', { objectProperty: { object: 'property' } }) +testJSONValueReviver('jsonReviver', -48269.592, function (k, v) { + return v * -1 +}, 48269.592) +testJSONValueReviver('jsonReviverInvalid', -48269.592, 'invalid reviver', -48269.592) + tape('cleanup', function(t) { s.close() t.end()