← Back to Blog

Build a JSON Formatter from Scratch in 50 Lines of JavaScript

April 19, 2026 3 min read By CodeTidy Team

The JSON Formatting Conundrum

Have you ever found yourself staring at a wall of minified JSON, struggling to make sense of the tangled mess of brackets and commas? You're not alone. Despite the importance of JSON in modern web development, formatting it can be a frustrating experience.

Table of Contents

  • Understanding the Problem
  • Building a Basic JSON Formatter
  • Adding Syntax Highlighting
  • Handling Errors and Edge Cases
  • Putting it all Together
  • Key Takeaways
  • FAQ

Understanding the Problem

JSON (JavaScript Object Notation) is a lightweight data interchange format that's widely used in web development. However, when working with large JSON datasets, the lack of formatting can make it difficult to read and understand. This is where a JSON formatter comes in – a tool that takes in a JSON string and outputs a beautifully formatted version.

Building a Basic JSON Formatter

We can start building a basic JSON formatter using JavaScript's built-in JSON.parse() and JSON.stringify() methods. The JSON.parse() method takes a JSON string and converts it into a JavaScript object, while JSON.stringify() takes a JavaScript object and converts it back into a JSON string. By using JSON.stringify() with the replacer function set to null and the space parameter set to 2, we can get a beautifully formatted JSON string.

const jsonString = '{"name":"John","age":30,"city":"New York"}';
const formattedJson = JSON.stringify(JSON.parse(jsonString), null, 2);
console.log(formattedJson);

This will output:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

Adding Syntax Highlighting

To make our formatter even more useful, we can add syntax highlighting using regular expressions. We'll use a simple regex pattern to match JSON keywords (such as "true", "false", and "null") and wrap them in <span> tags with a class of "json-keyword".

const syntaxHighlight = (jsonString) => {
  return jsonString.replace(/"(true|false|null)"/g, '<span class="json-keyword">$1</span>');
};

We can then use this function to highlight our formatted JSON string.

const formattedJson = JSON.stringify(JSON.parse(jsonString), null, 2);
const highlightedJson = syntaxHighlight(formattedJson);
console.log(highlightedJson);

Handling Errors and Edge Cases

Of course, not all JSON strings are created equal. Some may contain errors or edge cases that our formatter needs to handle. We can use a try-catch block to catch any errors that occur during parsing, and display a helpful error message to the user.

try {
  const formattedJson = JSON.stringify(JSON.parse(jsonString), null, 2);
  // ...
} catch (error) {
  console.error(`Error parsing JSON: ${error.message}`);
}

We can also add a check for invalid JSON input, and display an error message if the input is not a valid JSON string.

if (typeof jsonString !== 'string' || !jsonString.trim()) {
  console.error('Invalid JSON input');
}

Putting it all Together

Now that we have all the pieces in place, let's put them together into a single function that formats and highlights JSON, handles errors, and displays the result in a nice format. We'll also add a copy button to make it easy for users to copy the formatted JSON.

const jsonFormatter = (jsonString) => {
  try {
    const formattedJson = JSON.stringify(JSON.parse(jsonString), null, 2);
    const highlightedJson = syntaxHighlight(formattedJson);
    const container = document.getElementById('json-container');
    container.innerHTML = highlightedJson;
    const copyButton = document.getElementById('copy-button');
    copyButton.addEventListener('click', () => {
      navigator.clipboard.writeText(highlightedJson);
    });
  } catch (error) {
    console.error(`Error parsing JSON: ${error.message}`);
  }
};

Key Takeaways

  • Use JSON.parse() and JSON.stringify() to format JSON strings.
  • Add syntax highlighting using regular expressions.
  • Handle errors and edge cases using try-catch blocks and input validation.
  • Use a copy button to make it easy for users to copy the formatted JSON.

FAQ

Q: What is JSON and why do I need to format it?

A: JSON (JavaScript Object Notation) is a lightweight data interchange format that's widely used in web development. Formatting JSON makes it easier to read and understand, especially for large datasets.

Q: How do I use this JSON formatter in my own project?

A: Simply copy the jsonFormatter function into your project and call it with a JSON string as an argument. You'll need to create an HTML container element with an ID of "json-container" and a copy button element with an ID of "copy-button".

Q: Can I customize the syntax highlighting?

A: Yes! You can modify the syntaxHighlight function to use different regex patterns or add additional highlighting rules.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp