Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Added option for custom JSON parser, and test cases for json reviver …
…option and custom parser option
  • Loading branch information
vbelius committed Feb 9, 2024
commit ec4190a42caa61a9d1bedc4b0d41f5c3cd969d7a
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.

##### parser

The `parser` option can be used to supply a custom JSON parser used to
convert the request body to a Javascript object. If a `reviver` is
supplied, it is supplied as the second argument to this function.

Defaults to `JSON.parse`.

##### reviver

The `reviver` option is passed directly to `JSON.parse` as the second
Expand Down
17 changes: 12 additions & 5 deletions lib/types/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ function json (options) {
? bytes.parse(opts.limit || '100kb')
: opts.limit
var inflate = opts.inflate !== false
var parser = opts.parser || JSON.parse
var reviver = opts.reviver
var strict = opts.strict !== false
var type = opts.type || 'application/json'
Expand Down Expand Up @@ -89,12 +90,18 @@ function json (options) {

try {
debug('parse json')
return JSON.parse(body, reviver)
return parser(body, reviver)
} catch (e) {
throw normalizeJsonSyntaxError(e, {
message: e.message,
stack: e.stack
})
// Only normalize errors if using default parser
// Custom parsers might throw custom errors
if (parser === JSON.parse) {
throw normalizeJsonSyntaxError(e, {
message: e.message,
stack: e.stack
})
} else {
throw e
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions test/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,38 @@ describe('bodyParser.json()', function () {
})
})

describe('with reviver option', function () {
it('should use custom reviver', function (done) {
request(createServer({
reviver: function () {
return 'bar'
}
}))
.post('/')
.set('Content-Type', 'application/json')
.send('{"foo":""}')
.expect(200, '"bar"', done)
})

})

describe('with parser option', function () {
it('should use custom parser and pass reviver to it', function (done) {
request(createServer({
parser: function (body, reviver) {
return { foo: reviver() }
},
reviver: function () {
return 'bar'
}
}))
.post('/')
.set('Content-Type', 'application/json')
.send('{"str":""}')
.expect(200, '{"foo":"bar"}', done)
})
})

describe('with type option', function () {
describe('when "application/vnd.api+json"', function () {
before(function () {
Expand Down