or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdjson-parser.mdraw-parser.mdtext-parser.mdurlencoded-parser.md
tile.json

json-parser.mddocs/

JSON Parser

Middleware for parsing JSON request bodies. Only parses requests where the Content-Type header matches the type option and supports automatic inflation of compressed bodies.

Capabilities

JSON Parser Factory

Creates middleware that parses JSON bodies and populates req.body with the parsed data.

/**
 * Create middleware to parse JSON bodies
 * @param {object} [options] - Configuration options
 * @returns {function} Express middleware function
 */
function json(options?: {
  inflate?: boolean;
  limit?: number | string;
  reviver?: (key: string, value: any) => any;
  strict?: boolean;
  type?: string | string[] | ((req: IncomingMessage) => boolean);
  verify?: (req: IncomingMessage, res: ServerResponse, buf: Buffer, encoding: string) => void;
}): (req: IncomingMessage, res: ServerResponse, next: (err?: any) => void) => void;

Options

inflate

  • Type: boolean
  • Default: true
  • Description: When true, deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected

limit

  • Type: number | string
  • Default: '100kb'
  • Description: Controls the maximum request body size. If a number, specifies bytes; if a string, passed to the bytes library for parsing

reviver

  • Type: function
  • Default: undefined
  • Description: Passed directly to JSON.parse as the second argument for custom JSON parsing

strict

  • Type: boolean
  • Default: true
  • Description: When true, only accepts arrays and objects; when false, accepts anything JSON.parse accepts

type

  • Type: string | string[] | function
  • Default: 'application/json'
  • Description: Determines what media type the middleware will parse. Can be an extension name, MIME type, MIME type with wildcard, or function

verify

  • Type: function
  • Default: undefined
  • Description: Called as verify(req, res, buf, encoding) where buf is the raw request body Buffer. Can abort parsing by throwing an error

Usage Examples

Basic JSON parsing:

const bodyParser = require('body-parser');
const express = require('express');

const app = express();

// Parse JSON with default options
app.use(bodyParser.json());

app.post('/api/users', (req, res) => {
  console.log(req.body); // { name: "John", age: 30 }
  res.json({ received: req.body });
});

Custom options:

app.use(bodyParser.json({
  limit: '50mb',
  strict: false,
  type: 'application/*',
  verify: (req, res, buf, encoding) => {
    // Custom verification logic
    if (buf.length === 0) {
      throw new Error('Empty body not allowed');
    }
  }
}));

With reviver function:

app.use(bodyParser.json({
  reviver: (key, value) => {
    // Convert date strings to Date objects
    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) {
      return new Date(value);
    }
    return value;
  }
}));

Custom type checking:

app.use(bodyParser.json({
  type: (req) => {
    return req.headers['content-type'] === 'application/vnd.api+json';
  }
}));

Error Handling

The JSON parser can throw several types of errors:

  • 400 Bad Request: Invalid JSON syntax
  • 413 Payload Too Large: Body exceeds size limit
  • 415 Unsupported Media Type: Unsupported charset (only UTF-8 family supported)
app.use(bodyParser.json());

app.use((err, req, res, next) => {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).send('Invalid JSON');
  }
  if (err.type === 'entity.too.large') {
    return res.status(413).send('JSON too large');
  }
  next(err);
});