My JSON formatter is 80 lines of code. The hard part was everything else.

People keep asking how I built the formatter on jsonprocess.app. The core is 80 lines of code:

function processJson(input, action, indentSize = 2) {
  if (!input.trim()) return { success: true, data: "" }

  try {
    const parsed = JSON.parse(input)
    const result = action === "format"
      ? JSON.stringify(parsed, null, indentSize)
      : JSON.stringify(parsed)
    return { success: true, data: result }
  } catch (e) {
    const msg = e.message
    const pos = msg.match(/position\s+(\d+)/)
    return { success: false, error: msg, errorPosition: pos ? +pos[1] : undefined }
  }
}

That's it. That's the whole tool.

The hard part was everything around it:

  • Error messages humans can read. JSON.parse says Unexpected token } in JSON at position 1234. Users don't speak that. I extract the position and highlight the exact spot in red.
  • Big files. JSON.parse chokes past 10MB. I detect the size, process in chunks, show a progress bar, and use requestAnimationFrame so the tab doesn't die.
  • Syntax highlighting. No CodeMirror, no Monaco. Frameworks are a trap for a tool site. A regex and a <pre> is enough.
  • XSS. Highlighting means dangerouslySetInnerHTML. The first thing I did was sanitize with DOMPurify. If you copy my code, copy that part too.
  • Edge cases. Empty input. Bare strings. Numbers. Valid JSON that looks like it shouldn't be. Every one of them is a user who would have closed the tab.

Users think a formatter is magic. It's not magic. It's edge cases.

Use the formatter →

← All posts