MCPcopy Index your code
hub / github.com/expressjs/body-parser / createJsonParser

Function createJsonParser

lib/types/json.js:71–118  ·  view source on GitHub ↗

* Create a JSON parse function * * @param {object} [options] * @return {function} * @private

(options)

Source from the content-addressed store, hash-verified

69 * @private
70 */
71function createJsonParser (options) {
72 const reviver = options?.reviver
73 const strict = options?.strict !== false
74
75 if (strict) {
76 return function parse (body) {
77 if (body.length === 0) {
78 // special-case empty json body, as it's a common client-side mistake
79 // TODO: maybe make this configurable or part of "strict" option
80 return {}
81 }
82
83 const first = firstchar(body)
84 if (first !== '{' && first !== '[') {
85 debug('strict violation')
86 throw createStrictSyntaxError(body, first)
87 }
88
89 try {
90 debug('parse json')
91 return JSON.parse(body, reviver)
92 } catch (e) {
93 throw normalizeJsonSyntaxError(e, {
94 message: e.message,
95 stack: e.stack
96 })
97 }
98 }
99 }
100
101 return function parse (body) {
102 if (body.length === 0) {
103 // special-case empty json body, as it's a common client-side mistake
104 // TODO: maybe make this configurable or part of "strict" option
105 return {}
106 }
107
108 try {
109 debug('parse json')
110 return JSON.parse(body, reviver)
111 } catch (e) {
112 throw normalizeJsonSyntaxError(e, {
113 message: e.message,
114 stack: e.stack
115 })
116 }
117 }
118}
119
120/**
121 * Create strict violation syntax error matching native error.

Callers 1

jsonFunction · 0.85

Calls 3

firstcharFunction · 0.85
createStrictSyntaxErrorFunction · 0.85
normalizeJsonSyntaxErrorFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…