JSON Validator & Formatter

Validate and format JSON with detailed error messages, tree visualization, and syntax highlighting. Fix JSON errors instantly. Free online tool.

Advertisement

Check whether a block of JSON is actually valid — and find the exact character where it isn’t

Paste JSON into the left pane and it is parsed as you type. If it conforms, you get a green result plus a structural breakdown: object count, array count, total key count, maximum nesting depth, and byte size. If it does not conform, you get the parser’s message along with the line, column and character offset of the first thing it could not accept — which is nearly always the fastest route to the fix.

All of it runs in your browser. The text is parsed by your own JavaScript engine; nothing is posted to a server, nothing is written to a log, nothing is retained after you close the tab. That matters more for this tool than for most, because the JSON people need to validate in a hurry is usually an API response or a config file, and those routinely contain bearer tokens, connection strings and customer records. If you want a second layer of protection before pasting a payload into a chat message or a ticket, switch on auto-redact, which masks values that look like secrets — more on that below. If your goal is primarily to pretty-print or minify rather than to check conformance, the separate JSON formatter is the better fit.

What "valid" means here

JSON’s grammar is defined by RFC 8259 (and the identical ECMA-404). It is small enough to hold in your head, and validity means conforming to it exactly — not "looks like JSON" and not "my language’s parser accepted it". The permitted values are object, array, string, number, true, false and null, and that is the entire list. Everything people habitually add is a violation:

WrittenVerdictWhy
{"a": 1,}InvalidTrailing comma. Legal in JavaScript object literals, never in JSON.
{'a': 1}InvalidSingle quotes. Strings and keys must use double quotes.
{a: 1}InvalidUnquoted key. Keys are always quoted strings.
// commentInvalidJSON has no comment syntax at all.
{"a": undefined}Invalidundefined is not a JSON value. Use null.
{"a": NaN}InvalidNaN and Infinity are outside the number grammar.
{"a": .5}InvalidA number needs a leading digit: 0.5.
{"a": 01}InvalidLeading zeros are not permitted.
{"a": +1}InvalidA leading + is not allowed; only - is.
{"a": "x\'y"}Invalid\' is not a recognised escape. The legal ones are \" \\ \/ \b \f \n \r \t and \uXXXX.
"just a string"ValidRFC 8259 allows any value at the top level, not only objects and arrays.

That last row surprises people who learned JSON on an older parser. Under the original specification the document root had to be an object or an array; RFC 8259 relaxed that, so a bare string, number, true, false or null is a complete, valid JSON document. This validator accepts them.

Reading the error, not guessing at it

The parse error is reported with the raw engine message plus a computed line and column derived from the character offset. Two habits make that far more useful. First, trust the position but look before it: a parser reports where it gave up, which is usually one token past where you went wrong. A missing comma on line 12 is reported at the start of line 13, because line 12 read perfectly well until something appeared that could not follow it. Second, note that the offset is a character index into the raw text, so it stays accurate even in minified single-line JSON where the line number is uselessly always 1.

The most common real-world causes, roughly in order: a missing or extra comma between elements; an unescaped double quote inside a string value; unbalanced brackets after hand-editing; a Windows path such as C:\Users\name pasted into a string without doubling the backslashes; and a truncated response where the network connection dropped mid-body and the closing braces never arrived. That last one has a signature: the error lands at the very end of the input and complains about unexpected end of data.

The two things a parser will not tell you

Validation by parsing answers exactly one question — is this well-formed? Two categories of problem sail straight through, and both cause real production bugs.

Duplicate keys are legal and silently destructive

RFC 8259 says object member names should be unique, but it does not forbid repeats, and it leaves the behaviour for duplicates undefined. So {"role": "user", "role": "admin"} is well-formed JSON. Every JavaScript engine resolves it by keeping the last occurrence, which means this validator reports it as valid and the formatted output shows a single role of admin — the earlier value has vanished without a warning.

Be explicit about the consequence, because it is a genuine limitation of this page: if you need duplicate keys detected, a JSON.parse-based validator cannot do it, and neither can most of the ones you will find. What you can do here is spot the symptom. The statistics panel counts keys by walking the parsed structure, so it reports keys that survived. Compare that count against what you expect the payload to contain, or search the raw input for a key name and count the hits by eye. Different languages disagree on duplicates — some take the first, some take the last, some raise an error — so a document with repeats can genuinely mean different things to your service and to the client calling it.

Correct shape is a separate question from correct syntax

{"user_id": "42", "active": "yes", "created": null} is flawlessly valid JSON and probably a bug: an ID delivered as a string where the consumer expects a number, a boolean expressed as the word "yes", and a required timestamp that is null. No syntax validator can flag any of this, because nothing about it is malformed.

To be clear about scope: this tool does not perform JSON Schema validation. There is no field to supply a schema and no schema keyword support. What it gives you instead is the raw material for checking shape by hand, which for a one-off API payload is usually quicker than writing a schema anyway:

  • Tree view renders the parsed document as a collapsible hierarchy with each node’s inferred type, so you can see at a glance that user_id came back as a string rather than a number, or that a field you expected to be an array is an object with numeric keys.
  • Max depth tells you how deeply nested the structure is — useful when a consumer has a nesting limit, or when a response is unexpectedly one level deeper than the documentation implies because someone wrapped it in an envelope.
  • Object, array and key counts give you a cheap fingerprint. Two responses that should be equivalent but report different key counts differ somewhere, and that is a much faster signal than diffing thousands of lines.
  • Byte size is measured on the input as given, which is what you compare against a documented request-body limit.
  • Sort keys reorders every object alphabetically at every level. Applied to two payloads from different services, it makes them genuinely diffable, because key ordering is not significant in JSON but line-based diff tools do not know that.

Validating an API payload against what you expected

The usual situation is not an abstract file — it is a response that broke something. A workable sequence:

  • Paste the raw response body, exactly as received, before any tooling reformats it. If it fails to parse at all, you have learned something important: the problem is upstream, and you are probably looking at an HTML error page, a truncated body, or a gateway timeout page rather than JSON.
  • If it parses, switch to tree view and check the top level. A surprising share of "the API is broken" reports are an envelope mismatch — the client reads data.items and the server started returning items at the root, or the reverse.
  • Walk to the specific field that broke. Confirm its type, not just its presence. Numbers arriving as quoted strings is the single most common cross-language integration defect, and it is invisible until you look at the actual value.
  • Check for nulls where your consumer assumes a value. A field that is present but null and a field that is absent are different states, and code that only tests for presence will crash on the first.
  • Compare the key count and max depth against a known-good response from the same endpoint.

Large numbers, and why an ID can change value

A JSON number has no defined precision limit in the grammar, but JavaScript parses every number into a double-precision float. Integers beyond roughly nine quadrillion — 64-bit database IDs, Twitter-style snowflake identifiers, some financial values — cannot be represented exactly, and the parsed value is silently rounded to the nearest representable one. The document is valid, this validator reports it as valid, and the formatted output will show a number ending in a different digit from the one you pasted. If your identifiers are large integers, this is why the well-known advice is to transmit them as strings.

Auto-redact before you paste a payload into a ticket

Auto-redact masks values that look sensitive before they appear in the formatted output, and shows a count of how many it caught. It works two ways: by key name — anything matching patterns such as password, secret, token, api_key, authorization, client_secret, ssn, cvv and similar — and by value shape, recognising JWTs, bearer tokens, AWS access and secret keys, GitHub, Slack, Stripe and OpenAI key formats, PEM private-key headers, email addresses, credit-card-shaped digit runs and US phone numbers.

Treat it as a helpful net, not a guarantee. It matches known patterns; a secret stored under an unusual key name with no distinctive format will pass through untouched. Always read the redacted output before you share it. The redaction affects only the formatted output pane — your original input is left as typed.

Practical notes

Validation is debounced by a fraction of a second, so a large document does not re-parse on every keystroke, and the work runs as a low-priority update to keep typing responsive. Because parsing is done by the browser, the practical ceiling is your machine’s memory rather than a server-side upload limit — but genuinely large documents will make the tree view sluggish, and for multi-megabyte files a streaming parser in a real language is the right tool.

Two formats that are frequently mistaken for JSON and will not validate here: JSON Lines (also called NDJSON), where each line is an independent document and the file as a whole is not one — validate a single line at a time; and JSON5 or JSONC, the relaxed variants that permit comments, trailing commas and unquoted keys. Config files from tools that accept comments in their JSON are using an extension, not the standard, and a strict validator is correct to reject them.

What Is JSON Validation

JSON validation verifies that a string conforms to the JSON (JavaScript Object Notation) specification defined in RFC 8259. A valid JSON document must follow strict syntax rules: objects use curly braces with double-quoted keys, arrays use square brackets, strings must be double-quoted, and values must be one of six types (object, array, string, number, boolean, null). Even a single syntax error—a missing comma, unquoted key, or trailing comma—makes the entire document invalid.

JSON parsing errors are among the most common issues in web development, API integration, and configuration management. An API that returns malformed JSON breaks every client consuming it. A misconfigured JSON file prevents an application from starting. JSON validation catches these issues before they cause runtime failures, providing specific error messages that point to the exact location and nature of the problem.

How JSON Validation Works

A JSON validator parses the input string according to the JSON grammar, checking for:

Structural rules:

  • Objects: { "key": value } — keys must be double-quoted strings, separated by colons, pairs separated by commas
  • Arrays: [value, value] — values separated by commas
  • No trailing commas after the last element
  • No single quotes (only double quotes)
  • No comments (// or /* */ are invalid in JSON)
  • No undefined, NaN, or Infinity values

Common validation errors:

ErrorInvalid JSONCorrect JSON
Single quotes{'name': 'John'}{"name": "John"}
Trailing comma{"a": 1, "b": 2,}{"a": 1, "b": 2}
Unquoted key{name: "John"}{"name": "John"}
Single valueundefinednull
Comments{"a": 1} // comment{"a": 1}
No quotes on string{"name": John}{"name": "John"}

Schema validation goes beyond syntax to verify that JSON data conforms to an expected structure. JSON Schema (draft-07 or later) defines required fields, data types, value ranges, and patterns. For example, a schema can require that an "age" field is a positive integer and an "email" field matches an email pattern.

Common Use Cases

  • API development: Validate request and response payloads before processing to catch malformed data early
  • Configuration management: Verify JSON config files (package.json, tsconfig.json) before deployment
  • Data pipeline validation: Check JSON data quality at ingestion points in ETL pipelines
  • Testing: Validate API responses in automated test suites against expected schemas
  • Debugging: Identify the exact location and type of syntax errors in large JSON documents

Best Practices

  1. Validate early in the pipeline — Check JSON validity at API entry points, file upload handlers, and data ingestion stages
  2. Use JSON Schema for structural validation — Syntax validation alone doesn't catch wrong data types or missing required fields
  3. Provide meaningful error messages — Include line number, column, and expected vs. actual token in error output
  4. Handle encoding correctly — JSON must be UTF-8 encoded (RFC 8259); reject documents with BOM markers or other encodings
  5. Test with edge cases — Validate handling of deeply nested objects, very large numbers, Unicode escape sequences, and empty documents

Frequently Asked Questions

What is valid JSON syntax and what are common JSON errors?+

JSON syntax rules: (1) Data in name/value pairs: {"name":"value"}. (2) Strings use double quotes: "text" not 'text'. (3) Numbers: no quotes: 42, 3.14. (4) Booleans: true, false (lowercase). (5) Null: null (lowercase). (6) Arrays: [1, 2, 3]. (7) Objects: {"key":"value"}. (8) No trailing commas: [1,2,] invalid. (9) Keys must be strings: {name:"John"} invalid. Common errors: single quotes instead of double, trailing commas, unquoted keys, comments (not allowed in JSON), control characters unescaped. This tool identifies exact error location and suggests fixes.

What is the difference between JSON and JSON5?+

JSON: strict format defined by ECMA-404, double quotes required, no comments, no trailing commas, no unquoted keys. JSON5: relaxed superset, allows single quotes, supports comments (// and /* */), permits trailing commas, allows unquoted keys (if valid identifiers), supports more number formats (hex, Infinity, NaN). Example valid JSON5 but invalid JSON: {unquoted: 'single quotes', trailing: true, /* comment */}. When to use: JSON for APIs and data interchange (universal support), JSON5 for config files (better human readability), JSONC (JSON with comments) for VS Code settings. Most APIs require strict JSON; use JSON5 only when explicitly supported.

How do I validate JSON against a schema?+

JSON Schema defines structure/validation rules. Define schema: {"type":"object","properties":{"name":{"type":"string"},"age":{"type":"number","minimum":0}},"required":["name"]}. Validation libraries: JavaScript: ajv, jsonschema. Python: jsonschema. PHP: justinrainbow/json-schema. Java: everit-org/json-schema. Common validators: type (string, number, boolean, object, array, null), required fields, min/max values, string patterns (regex), enum (allowed values), nested objects/arrays. Use cases: API request validation, config file validation, form validation, data integrity. Validation errors show: field path, constraint violated, expected vs actual value. This basic tool validates syntax; use schema validators for structural validation.

What are JSON formatting best practices?+

Formatting standards: Indentation: 2 spaces (most common) or 4 spaces, never tabs. Spacing: space after colon "key": "value", no space before colon, space after comma. Line breaks: each property on new line for readability, arrays can be inline if short. Key ordering: alphabetical or logical grouping for consistency. Minified JSON: no whitespace, smallest size for APIs. Pretty JSON: indented, readable for humans. When to minify: production APIs (save bandwidth), when to pretty: development, debugging, config files, documentation. Tools: JSON.stringify(obj, null, 2) for pretty, JSON.stringify(obj) for minified. This tool offers both beautify and minify modes with customizable indentation.

How do I handle large JSON files?+

Challenges: browser memory limits (~100MB-1GB depending on RAM), parse time increases with size, UI freezes during processing. Solutions: Streaming: parse incrementally, don't load entire file, Node.js: JSONStream, oboe.js, clarinet. Browser: chunked reading with FileReader. Pagination: load data in chunks, virtual scrolling for display, lazy loading on demand. Server-side: process large JSON server-side, return paginated results, use database for querying. Compression: gzip reduces size 70-90%, serve as .json.gz, decompress server-side. Alternative formats: CSV for tabular data, binary formats (Protocol Buffers, MessagePack) for efficiency. This browser tool handles ~10MB comfortably; use command-line tools (jq) for larger files.

What is the difference between JSON.parse and JSON.stringify?+

JSON.parse(): converts JSON string to JavaScript object. Input: string '{"name":"John"}', output: object {name:"John"}. Throws SyntaxError on invalid JSON. Optional reviver parameter for custom parsing. Use: deserialize API responses, read stored JSON, process JSON files. JSON.stringify(): converts JavaScript object to JSON string. Input: object {name:"John"}, output: string '{"name":"John"}'. Optional replacer for filtering/transforming, optional space parameter for pretty printing. Handles: undefined (omitted), functions (omitted), Date objects (converted to ISO string), circular references (throws error). Use: send data to APIs, store objects in localStorage, create JSON files. Round-trip: JSON.parse(JSON.stringify(obj)) clones objects (loses functions/undefined).

How do I safely parse untrusted JSON?+

Security considerations: JSON.parse is safe (doesn't execute code), unlike eval (never use eval for JSON!). Attacks to prevent: (1) Large JSON (DoS): limit file size before parsing, set memory limits, timeout long parsing. (2) Deep nesting (stack overflow): validate depth before parsing, limit recursion. (3) Prototype pollution: validate object keys, avoid __proto__, constructor, prototype. Validation steps: check content-type header (application/json), limit request size (e.g., 1MB), try-catch parse errors, validate against schema, sanitize data before use, rate limit API endpoints. Never: use eval(), trust parsed data implicitly, allow arbitrary key names without validation. This tool helps identify malformed JSON before processing in applications.

What are common JSON use cases and alternatives?+

JSON use cases: REST APIs (request/response bodies), config files (package.json, settings), data storage (NoSQL databases, localStorage), data interchange (between services), mobile apps (API communication), web applications (AJAX responses). Alternatives: XML (more verbose, better for documents), YAML (human-readable, for configs), TOML (simple configs), Protocol Buffers (binary, efficient), MessagePack (binary JSON), CSV (tabular data), JSON Lines (JSONL) (streaming logs). Choose JSON for: APIs (universal support), JavaScript applications (native support), human-readable data exchange. Choose alternatives for: large datasets (CSV, Parquet), high performance (Protocol Buffers), config readability (YAML, TOML), streaming (JSON Lines). JSON remains most popular for APIs due to simplicity and ubiquity.

This tool is provided for informational and educational purposes only. All processing happens in your browser — no data is sent to or stored on our servers. While we strive for accuracy, we make no warranties about the completeness or reliability of results.