3 * Copyright(c) 2014 Jonathan Ong
4 * Copyright(c) 2014-2015 Douglas Christopher Wilson
11 * Module dependencies.
15 var bytes = require('bytes')
16 var contentType = require('content-type')
17 var createError = require('http-errors')
18 var debug = require('debug')('body-parser:json')
19 var read = require('../read')
20 var typeis = require('type-is')
29 * RegExp to match the first non-space in a string.
31 * Allowed whitespace is defined in RFC 7159:
35 * %x09 / ; Horizontal tab
36 * %x0A / ; Line feed or New line
37 * %x0D ) ; Carriage return
40 var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/
43 * Create a middleware to parse JSON bodies.
45 * @param {object} [options]
50 function json(options) {
51 var opts = options || {}
53 var limit = typeof opts.limit !== 'number'
54 ? bytes.parse(opts.limit || '100kb')
56 var inflate = opts.inflate !== false
57 var reviver = opts.reviver
58 var strict = opts.strict !== false
59 var type = opts.type || 'application/json'
60 var verify = opts.verify || false
62 if (verify !== false && typeof verify !== 'function') {
63 throw new TypeError('option verify must be function')
66 // create the appropriate type checking function
67 var shouldParse = typeof type !== 'function'
71 function parse(body) {
72 if (body.length === 0) {
73 // special-case empty json body, as it's a common client-side mistake
74 // TODO: maybe make this configurable or part of "strict" option
79 var first = firstchar(body)
81 if (first !== '{' && first !== '[') {
82 debug('strict violation')
83 throw new SyntaxError('Unexpected token ' + first)
88 return JSON.parse(body, reviver)
91 return function jsonParser(req, res, next) {
93 return debug('body already parsed'), next()
96 req.body = req.body || {}
98 // skip requests without bodies
99 if (!typeis.hasBody(req)) {
100 return debug('skip empty body'), next()
103 debug('content-type %j', req.headers['content-type'])
105 // determine if request should be parsed
106 if (!shouldParse(req)) {
107 return debug('skip parsing'), next()
110 // assert charset per RFC 7159 sec 8.1
111 var charset = getCharset(req) || 'utf-8'
112 if (charset.substr(0, 4) !== 'utf-') {
113 debug('invalid charset')
114 next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
121 read(req, res, next, parse, debug, {
131 * Get the first non-whitespace character in a string.
133 * @param {string} str
139 function firstchar(str) {
140 var match = firstcharRegExp.exec(str)
141 return match ? match[1] : ''
145 * Get the charset of a request.
147 * @param {object} req
151 function getCharset(req) {
153 return contentType.parse(req).parameters.charset.toLowerCase()
160 * Get the simple type checker.
162 * @param {string} type
166 function typeChecker(type) {
167 return function checkType(req) {
168 return Boolean(typeis(req, type))