Why a JSON Minifier Should Validate First

AIGClub Team

Many minifying failures are not minifier failures. The input is often not standard JSON. Parsing first exposes syntax problems before compact output is generated.

A JSON minifier should validate first because only valid JSON can be safely compacted. Common errors include single quotes, unquoted keys, trailing commas, comments, mismatched brackets, unescaped line breaks inside strings, and copied text that is missing the beginning or end.

Why not just remove whitespace?

  1. Spaces inside JSON strings can be real data. A global whitespace replacement cannot reliably tell layout whitespace from content. Parsing JSON first makes that distinction before serializing compact output.
  2. Direct cleanup can also hide copied fragments, missing brackets, or comments. A minifier should stop on invalid input instead of producing a result that looks usable but is not valid JSON.

Common errors before minifying

  1. A frequent mistake is JavaScript object syntax instead of JSON: {'state':'ready',} fails because keys/strings use single quotes and the last member has a trailing comma. Another common issue is an incomplete structure such as {"items":[1,2} with mismatched closing characters.
  2. String escaping can fail when a copied value contains a raw line break, backslash, or quote. Reduce the input to the smallest failing fragment; after fixing {"note":"line 1 line 2"} to use the two-character \n escape, rerun validation before minifying.

A quick troubleshooting flow

  1. First confirm the top-level value is an object, array, string, number, boolean, or null. Then check that object keys and strings use double quotes, fields have commas between them, and arrays or objects close correctly.
  2. If the content came from logs or code, remove prefixes, timestamps, comments, and wrapper text so only the JSON fragment remains. Format the fragment to review structure, then minify it for copying.

Frequently asked questions

Can JSON contain comments?
Standard JSON does not include comments. Some configuration formats allow comments, but they are not strict JSON and cannot be handled directly by JSON.parse.
Why does an object with single quotes fail?
JSON strings and object keys must use double quotes. Single quotes belong to JavaScript syntax, not standard JSON syntax.
Is the parser error position always the root cause?
It is useful, but not always the exact root cause. Missing commas or brackets can make the parser report a position after the real mistake.
Back to blog