Find the error in invalid JSON and format it
Formatting JSON is the easy part. The hard part is a file that will not parse and an error message that points at a position you cannot see, often because the real mistake is a few characters earlier.
The error position is a place to look, not a diagnosis
A parser reports where it could no longer continue, which is often just after the actual mistake. A missing comma before a new key shows up on the next key; a trailing comma before a closing brace shows up on the brace. Look at the line named in the error and the line above it together.
Common causes are trailing commas, single quotes instead of double quotes, comments pasted from documentation, and unquoted keys. All of them are syntax, not data, and all of them can be fixed without touching the values.
Syntax errors and data errors need different fixes
Once the file parses, the remaining problems are about meaning: a number stored as a string, a date in an inconsistent format, a missing field in one of a hundred records. These will not produce an error, which is why a successful format operation is not a validation of the content.
A useful check is to compare the formatted result with what the consumer expects. A required key that never appears will still fail downstream even though the braces line up.
Keep the compact form on purpose
Indented JSON is for reading and review; compact JSON is for transferring or storing. Do not commit a file to a repository, or send it to an API, in a form that differs only by whitespace and nesting. Pick one form for each use and keep the original until the change has been verified.
If the file is too large to read comfortably, formatting with indentation can make it slower to handle. Count lines and bytes first, and work on a valid subset only if you know the structure.
A reliable sequence
- Paste the original into a scratch copy, never edit the only version in place
- Format with the indent style used by the project
- If it fails, check the reported line and the one before it
- Check for comments and single quotes, which JSON does not allow
- After it parses, compare keys and value types with the expected shape
- Compact again only when you know the destination wants compact output