JSON Parse & Stringify

Practical parsing rules, error handling, and serialization.

On this page

Parsing vs stringifying

JSON parsing turns a JSON string into a native data structure. Stringifying does the reverse: it converts data into a JSON string. In APIs, servers usually parse incoming JSON bodies and stringify outgoing responses.

JavaScript basics

const obj = JSON.parse('{"id":42,"name":"Ada"}');
const text = JSON.stringify({ id: 42, name: "Ada" });

Parsing failures are normal

Clients can send malformed JSON, wrong Content-Type, or unexpected types. Treat parse errors as client errors and return a clear 400 response.

Example: handle invalid JSON (concept)

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "title": "Invalid JSON",
  "status": 400,
  "detail": "Request body must be valid JSON."
}

Stringify options you actually use

  • Pretty print: useful for logs and debugging (not for production responses unless needed)
  • Replacer: filter fields (be careful: it can hide bugs)

Example: safe response serialization

const safe = {
  id: user.id,
  name: user.name,
  createdAt: user.createdAt.toISOString()
};

res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(safe));

Numbers and dates

  • JSON has no date type. Use ISO 8601 strings.
  • Large integers can lose precision in JavaScript. Consider sending big IDs as strings.

Common mistakes

  • Accepting JSON without checking Content-Type
  • Returning non-JSON (HTML error pages) with Content-Type: application/json
  • Inconsistent field types across responses

Checklist

  • Invalid JSON returns 400 with JSON error body.
  • Dates are ISO strings, not locale strings.
  • Big IDs have a deliberate strategy (number vs string).