DevToolsForYou

JSON Formatter, Minifier, and Validator in JavaScript / Node.js — Code Examples

JSON Formatter, Minifier, and Validator in JavaScript / Node.jsUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

JavaScript has JSON.parse() and JSON.stringify() built in. Use the space parameter of JSON.stringify() for pretty-printing.

JavaScript
// Parse JSON string → object
const obj = JSON.parse('{"name":"Alice","age":30}');
console.log(obj.name); // Alice

// Serialize object → JSON string
const json = JSON.stringify(obj);
console.log(json); // {"name":"Alice","age":30}

// Pretty-print with 2-space indentation
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
// {
//   "name": "Alice",
//   "age": 30
// }

// Replacer function — exclude null values
const filtered = JSON.stringify(
  { a: 1, b: null, c: "hello" },
  (key, value) => (value === null ? undefined : value),
  2
);

// Reviver — parse dates automatically
const withDates = JSON.parse(
  '{"created":"2023-11-14T22:13:20Z"}',
  (key, value) =>
    typeof value === "string" && /^d{4}-d{2}-d{2}T/.test(value)
      ? new Date(value)
      : value
);
console.log(withDates.created instanceof Date); // true
Notes & gotchas
  • JSON.parse() throws SyntaxError on invalid JSON — wrap in try/catch.
  • JSON.stringify() silently drops undefined values, functions, and Symbol keys.
  • The replacer function in JSON.stringify() lets you control which keys are included.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages