Skip to main content

    JSON Formatter & Validator

    Format, validate, and minify JSON instantly. Pretty-print with 2 or 4 space indentation. 100% browser-based.

    Free to use. Runs in your browser.

    Paste JSON to format with proper indentation or minify to a single line. Invalid JSON shows the exact error.

    What Is JSON and Why Format It?

    JSON (JavaScript Object Notation) is the lingua franca of the web. Every API you've ever used almost certainly speaks JSON. It's human-readable in theory, but in practice, minified JSON from an API response is a wall of brackets, commas, and nested objects that makes your eyes bleed. That's where formatting comes in.

    Pretty-printing JSON adds indentation and line breaks so you can actually see the structure. Nested objects become obvious. Missing commas jump out. A 500-character blob becomes a clear, scannable tree. It's the difference between reading a paragraph with no spaces and reading one with proper formatting.

    This tool runs entirely in your browser, your JSON never leaves your device. Paste it in, format or minify, copy the result. No API calls, no data logging, no privacy concerns. That matters when you're debugging API responses that contain auth tokens, user data, or production database records.

    JSON Data Types at a Glance

    TypeExampleRules
    String"name": "Alice"Always double-quoted
    Number"age": 30No quotes, supports decimals and negatives
    Boolean"active": trueLowercase true/false only
    Null"deleted": nullLowercase null (not undefined)
    Array"tags": ["a", "b"]Ordered list, mixed types allowed
    Object{"key": "value"}Unordered key-value pairs

    JSON doesn't support: comments, trailing commas, single quotes, undefined, NaN, Infinity, dates (use ISO 8601 strings), or functions. These are the most common reasons JSON fails to parse.

    JSON Error Reference

    When JSON.parse() fails, the error message can be cryptic. Search for your error message below to find the cause and fix.

    Error MessageCauseFix
    Unexpected token 'Single quotes around keys or valuesReplace all single quotes with double quotes: 'name' → "name"
    Unexpected end of JSON inputMissing closing bracket, brace, or truncated responseCount opening/closing pairs, every { needs } and every [ needs ]
    Expected ',' or '}'Trailing comma after last item in object/arrayRemove the comma after the last property: {"a": 1,} → {"a": 1}
    Unexpected token /JavaScript-style comments in JSONRemove all // and /* */ comments, JSON doesn't support them
    Bad escaped characterUnescaped backslash or quote inside stringEscape special chars: use \\ for backslash, \" for quote in strings
    Unexpected token uundefined value (not valid JSON)Replace undefined with null, JSON only supports null, not undefined
    Unexpected number / NaN / InfinityNaN or Infinity in outputNaN and Infinity aren't valid JSON. Convert to null or a string first
    Unterminated stringString contains unescaped newlineUse \n for newlines inside strings, not actual line breaks
    Duplicate keySame key appears twice in an objectRemove the duplicate. Last value wins in most parsers but it's ambiguous
    json.decoder.JSONDecodeErrorInvalid JSON passed to json.loads()Check for BOM (byte order mark), trailing content, or encoding issues
    JsonSyntaxExceptionMalformed JSON stringValidate your JSON first. Check for unquoted keys or JavaScript syntax
    SyntaxError: JSON.parseAny invalid JSON passed to JSON.parse()Wrap in try/catch. Log the raw string to see what's actually being parsed
    Cannot read property of undefinedAccessing nested property that doesn't existUse optional chaining: data?.user?.name instead of data.user.name
    Maximum call stack size exceededCircular reference in JSON.stringify()Remove circular refs before stringifying, or use a replacer function

    Showing 14 of 14 errors.

    HTTP Status Codes (API Quick Reference)

    When you're formatting JSON from an API response, the status code tells you what happened before you even look at the body. Search by code number or description.

    CodeStatusMeaning
    200OKRequest succeeded. The response body contains the requested data.
    201CreatedNew resource was created successfully.
    204No ContentRequest succeeded but there's no response body.
    301Moved PermanentlyResource has moved to a new URL permanently.
    302FoundResource is temporarily at a different URL.
    304Not ModifiedCached version is still valid.
    400Bad RequestThe request was malformed or missing required fields.
    401UnauthorizedAuthentication is required or has failed.
    403ForbiddenYou're authenticated but don't have permission.
    404Not FoundThe requested resource doesn't exist.
    405Method Not AllowedHTTP method not supported for this endpoint.
    409ConflictRequest conflicts with current state of the resource.
    413Payload Too LargeRequest body exceeds the server's size limit.
    415Unsupported Media TypeContent-Type header is wrong.
    422Unprocessable EntityJSON is valid but the data doesn't pass validation.
    429Too Many RequestsRate limit exceeded.
    500Internal Server ErrorSomething broke on the server side.
    502Bad GatewayServer got an invalid response from upstream.
    503Service UnavailableServer is overloaded or down for maintenance.
    504Gateway TimeoutUpstream server didn't respond in time.

    Showing 20 of 20 codes.

    Format vs Minify: When to Use Each

    Format (pretty-print)

    Use during development, debugging, code review, and documentation. Readable structure helps you spot issues. Choose 2-space indent for compact output, 4-space for maximum readability, or tab indent if that's your project's standard.

    Minify (compact)

    Use for production APIs, config files, localStorage, and data transfer. Removes all whitespace to reduce payload size. A 10 KB formatted JSON might minify to 6 KB, a 40% saving that adds up at scale, especially over slow mobile connections.

    Payload SizeFormattedMinifiedSavings
    Small API response2 KB1.2 KB40%
    Product catalogue500 KB280 KB44%
    GeoJSON dataset5 MB2.8 MB44%
    + gzip compression5 MB → 800 KB2.8 MB → 650 KB84-87%

    Key insight: Gzip compression (which most servers apply automatically) dramatically reduces size regardless of formatting. The real win from minification is eliminating whitespace before gzip, but the difference is smaller than you'd expect. Format for development, minify for production, and make sure gzip is enabled on your server.

    JSON vs Alternatives

    FormatCommentsReadableBest For
    JSONNoGood (formatted)APIs, data transfer, configs
    YAMLYesExcellentDocker, CI/CD, Kubernetes
    TOMLYesExcellentApp config (Cargo, pyproject)
    JSON5YesGreatConfig files where comments help
    XMLYesPoor (verbose)Legacy systems, SOAP, SVG
    Protocol BuffersYes (.proto)No (binary)High-performance gRPC APIs
    MessagePackNoNo (binary)Compact data transfer

    What this means for you: JSON won the API format war because it's native to JavaScript and simple to parse in every language. Use YAML or TOML for config files where you need comments. Use JSON for data exchange. If you need comments in JSON, use JSON5 or JSONC (JSON with Comments, what VS Code uses for settings).

    Worked Example: Debugging a Failing API Call

    The situation: Dev is building a React app that calls a REST API. The fetch request keeps failing with "SyntaxError: Unexpected token" when calling JSON.parse(). The raw response looks like a wall of text.

    Step 1: Copy the raw response

    In the browser DevTools Network tab, find the failing request, click the Response tab, and copy the entire response body. It's 2,000 characters of minified JSON, impossible to read.

    Step 2: Paste into the formatter

    Pasting into this tool immediately shows a validation error: "Unexpected token at position 847." The tool highlights the problem area. It turns out the API returned a 500 error page (HTML, not JSON), the response starts with <!DOCTYPE html>.

    Step 3: Check the status code

    Back in DevTools: the response status is 500 Internal Server Error. The server crashed and returned an HTML error page instead of JSON. The fix is server-side, the endpoint needs error handling that returns JSON even on failure.

    Step 4: Add defensive parsing

    In the meantime, wrap the client-side parse in a try/catch: check response.ok before calling response.json(), and handle non-JSON responses gracefully instead of crashing.

    JSON Best Practices

    Use consistent naming

    Pick camelCase or snake_case and stick with it across your entire API. Mixing "firstName" and "last_name" in the same response confuses every developer who touches it.

    Dates as ISO 8601 strings

    Always use "2026-04-15T14:30:00Z" format. Not timestamps, not "April 15th", not "15/04/2026". ISO 8601 is unambiguous, sortable, and parseable in every language.

    Null vs missing keys

    Be deliberate: "email": null means "this field exists but has no value." Omitting the key entirely means "this field doesn't apply." Document which approach your API uses.

    Always validate on the server

    Never trust incoming JSON. Validate types, required fields, and value ranges. A missing field that your code assumes exists will crash at 3am on a Friday.

    Common Mistakes

    Trailing commas

    JavaScript allows trailing commas everywhere, so you forget JSON doesn't. [1, 2, 3,] is valid JS but invalid JSON. Always remove the comma after the last element.

    Stringifying twice

    Calling JSON.stringify() on a string that's already JSON wraps it in extra quotes and escapes. You get "{\"name\":\"Alice\"}" instead of '{"name":"Alice"}'. Check if the input is already a string before stringifying.

    Not checking Content-Type

    Your API returns HTML error pages, but your code blindly calls JSON.parse() on every response. Always check that Content-Type is application/json before parsing.

    Logging sensitive data

    Pretty-printing an API response to console.log in production, including auth tokens, API keys, and user PII. Use environment checks to suppress JSON logging in production.

    Huge JSON in localStorage

    Storing megabytes of JSON in localStorage (5 MB limit in most browsers). It blocks the main thread during read/write. Use IndexedDB for large datasets, localStorage for small config only.

    No error handling for parse

    JSON.parse() throws on invalid input. Always wrap it in try/catch. An uncaught parse error can crash your entire app if it's in a request handler or event listener.

    Related Tools

    How to use this tool

    1

    Paste your raw JSON into the input area

    2

    Click Format to pretty-print or Minify to compress

    3

    Copy the result or view syntax-highlighted output

    Common uses

    • Debugging API responses during development
    • Formatting config files for readability
    • Minifying JSON payloads to reduce file size
    • Validating JSON structure before deployment

    Share this tool

    Frequently Asked Questions

    What does this JSON formatter do?
    It takes raw JSON and either pretty-prints it with proper indentation (2 spaces, 4 spaces, or tabs) or minifies it to a single line. It also validates your JSON and shows the exact error location if anything's wrong.
    Is my JSON sent to a server?
    No. All formatting, minification, and validation happens entirely in your browser using JavaScript's built-in JSON.parse() and JSON.stringify(). Your data never leaves your device.
    Can this tool fix broken JSON?
    It can't auto-fix invalid JSON, but it shows you the exact error message from the parser, including the position where the error occurs. Common fixes: add missing commas, close unclosed brackets, wrap keys in double quotes, remove trailing commas.
    What's the difference between formatting and minifying JSON?
    Formatting adds whitespace and indentation to make JSON human-readable. Minifying strips all unnecessary whitespace to reduce file size. A 10KB formatted JSON file might be only 4KB minified, that matters for API payloads and config files.
    Why do JSON keys need double quotes?
    The JSON specification requires all keys to be wrapped in double quotes. Single quotes, unquoted keys, and backticks are invalid JSON (even though JavaScript objects accept them). This is the most common JSON validation error developers hit.
    Can JSON have comments?
    No. The JSON specification does not allow comments of any kind, no //, no /* */, no # comments. If you need comments in config files, use JSONC (JSON with Comments) which tools like VS Code support, or switch to YAML or TOML.
    What's the maximum JSON size this can handle?
    There's no hard limit in our tool. Modern browsers handle JSON strings of several hundred MB. For very large files (100MB+), you might notice a brief pause during formatting. If your JSON is enormous, consider using jq on the command line instead.
    Why does my JSON have trailing comma errors?
    JSON doesn't allow trailing commas after the last item in an array or object. [1, 2, 3,] is invalid JSON but valid JavaScript. Remove the comma after the last element. Many formatters and linters can auto-fix this.
    How do I validate JSON in JavaScript?
    Wrap JSON.parse() in a try/catch: try { JSON.parse(str); } catch (e) { console.error(e.message); }. If it throws, the string isn't valid JSON. The error message tells you exactly what's wrong and where.
    What's the difference between JSON and a JavaScript object?
    JSON is a text format with strict rules: double-quoted keys, no functions, no undefined, no trailing commas, no comments. JavaScript objects are far more flexible. JSON is always valid JS, but JS objects aren't always valid JSON.
    Can I format JSON with 4 spaces or tabs?
    Yes. This tool offers 2-space (default), 4-space, and tab indentation. The choice is mostly personal preference, though 2 spaces is the most common in web development. JSON.stringify(obj, null, 2) uses 2 spaces; replace 2 with '\t' for tabs.
    How do I minify JSON for production?
    Paste your JSON and click Minify. This removes all whitespace, newlines, and indentation, producing the smallest possible valid JSON string. For build pipelines, use JSON.stringify(obj) without the third argument, it produces minified output by default.

    Results are for general informational purposes only and should be checked before use. They are not professional advice. See our Disclaimer and Terms of Service.