JSON is a small data format, but production JSON bugs are rarely small. A missing quote can break an API response, a duplicate key can hide data, a large number can lose precision, and a payload that parses successfully can still be unsafe or structurally wrong.
This guide focuses on practical JSON tips for developers: valid syntax, validation, debugging, formatting, schema contracts, security limits, and examples you can apply when building APIs, configuration files, logs, webhooks, and data exports.
What is valid JSON?
JSON is a text-based data interchange format. A JSON document contains one JSON value: an object, array, string, number, boolean, or null.
The syntax is stricter than JavaScript object syntax. Property names must use double quotes, strings must use double quotes, trailing commas are invalid, comments are invalid, and special JavaScript values such as undefined, NaN, functions, regular expressions, and BigInt are not JSON values.
{
"id": "user_123",
"active": true,
"roles": ["admin", "editor"],
"profile": {
"name": "Ava Chen",
"timezone": "UTC"
},
"deletedAt": null
}Use ToolMint's JSON Formatter when you need to format, minify, sort, or inspect JSON quickly.
JSON values at a glance
| JSON value | Example | Practical note |
|---|---|---|
| Object | {"name":"ToolMint"} |
Keys are strings and should be unique. |
| Array | ["read","write"] |
Order matters inside arrays. |
| String | "hello" |
Must use double quotes. |
| Number | 42 |
Has no separate integer or decimal type in JSON. |
| Boolean | true |
Lowercase only: true or false. |
| Null | null |
Means an explicit empty value, not missing. |
Use double quotes, not JavaScript object syntax
This is valid JavaScript, but it is not valid JSON:
{
id: 'user_123',
active: true,
}Valid JSON requires double-quoted keys and strings:
{
"id": "user_123",
"active": true
}The distinction matters when copying examples from source code into API docs, request bodies, environment configuration, or webhooks. A JavaScript object literal can contain conveniences that a JSON parser must reject.
Avoid trailing commas and comments
Trailing commas are a common source of JSON.parse failures.
{
"name": "ToolMint",
"category": "Developer",
}The comma after "Developer" makes the document invalid. Comments are also not part of standard JSON:
{
"timeout": 5000
// This comment is not allowed in JSON.
}Some configuration formats intentionally extend JSON, but do not assume those extensions work in APIs, browsers, webhooks, structured data, package metadata, or third-party integrations.
Escape strings deliberately
JSON strings support escape sequences such as \", \\, \n, and Unicode escapes like \u00A9. You usually should not hand-escape JSON strings. Let a serializer do it.
const payload = {
message: 'He said "ship it" on line 1\nThen left a note.'
}
const json = JSON.stringify(payload)Manual escaping is where bugs appear: broken line breaks, invalid backslashes, and accidental HTML or script injection. Serialize data with JSON.stringify and validate the result when integrating with systems that expect strict JSON.
Treat duplicate object keys as a bug
JSON object member names should be unique for interoperability. Some parsers keep the last value, some tools warn, and some systems may behave differently.
{
"role": "viewer",
"role": "admin"
}Do not rely on duplicate key behavior. JSON.parse keeps the last value in this example, so a schema check on the parsed object cannot recover the discarded "viewer" value. Check the source text for duplicates before parsing or reserializing it; JSON Formatter reports duplicate names before export. A text diff can show differences between two source payloads, but it is not a duplicate-key validator.
Parse errors should become useful errors
Never let raw parsing failures become confusing server errors. Catch parsing errors and return a specific validation response.
export async function parseJsonRequest(request) {
try {
return { ok: true, value: await request.json() }
} catch (error) {
if (!(error instanceof SyntaxError)) throw error
return { ok: false, error: "Invalid JSON body" }
}
}Check result.ok before reading result.value. The wrapper keeps a valid payload such as {"error":"domain value"} distinct from a parse failure. Request-body read failures are rethrown; this helper does not set an HTTP response status or enforce a body-size limit. Apply those policies at the request boundary. MDN documents the different Request.json() exceptions.
Parsing tells you whether the document is syntactically valid. It does not tell you whether required fields exist, whether an email is valid, whether a user can access an account, or whether a value is safe to store.
Validate structure after parsing
Use JSON Schema or a runtime validation library when the payload is more than a quick internal object. A schema turns assumptions into a contract.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email", "roles"],
"additionalProperties": false,
"properties": {
"id": { "type": "string" },
"email": { "type": "string", "format": "email" },
"roles": {
"type": "array",
"items": { "type": "string" }
}
}
}In Draft 2020-12, format can be annotation-only: the presence of "format": "email" is not a portable guarantee that a validator will reject an invalid address. Enable supported format assertions in your validator and test a failing value. Format validation also does not prove ownership or deliverability of a mailbox. See the JSON Schema format guidance.
Try these synthetic inputs against the schema above:
| Input | Syntax check | Schema result |
|---|---|---|
{"id":"user_123","email":"reader@example.com","roles":["reader"]} |
Parses | Meets the illustrated contract |
{"id":123,"email":"reader@example.com","roles":"reader"} |
Parses | Fails the declared types for id and roles |
{"id":"user_123","email":"not-an-address","roles":["reader"]} |
Parses | Fails only when the validator enforces the email format |
The JSON Schema Validator supports this draft and enforces its supported formats. Use the local schema validation guide for the separate tool workflow. Passing the schema does not authorize a caller to assign roles.
Schema validation is especially useful for API contracts, event payloads, imports, exports, partner integrations, and data pipelines. Keep business rules close to the application too; schema validation should not become the only security boundary.
Format for humans, minify for transport
Pretty JSON is easier to debug. Minified JSON is smaller on the wire.
For source JSON that may contain large numeric IDs, follow the formatting guide that preserves number tokens. The JSON.stringify examples below serialize values already represented in JavaScript; they cannot recover precision lost during parsing.
const pretty = JSON.stringify(data, null, 2)
const compact = JSON.stringify(data)Use readable formatting in logs, docs, examples, pull requests, and manual debugging. Use compact JSON for production responses unless readability is part of the product experience.
Be careful with numeric precision
JSON numbers do not specify JavaScript's exact runtime behavior. In JavaScript, numbers are IEEE 754 double-precision values, so integers beyond Number.MAX_SAFE_INTEGER can lose precision.
JSON.parse('{"invoiceId":9007199254740993}')
// { invoiceId: 9007199254740992 }For database IDs, payment references, large counters, and externally assigned identifiers, serialize the value as a string when exact preservation matters.
{
"invoiceId": "9007199254740993"
}Do not assume object key order is meaningful
JSON arrays are ordered. JSON object members should not be treated as semantically ordered data.
Stable key ordering is still useful for diffs, snapshots, tests, cache keys, and content hashes, but it should be a serialization strategy, not a data-model assumption.
const first = '{"b":2,"a":1}'
const second = '{"a":1,"b":2}'
JSON.stringify(JSON.parse(first)) === JSON.stringify(JSON.parse(second))
// false: native serialization retains this difference in member orderThese documents contain the same object members but different text. Hash Generator compares exact input bytes; it does not decide semantic JSON equality or canonicalize a document.
Readable key sorting is not a cryptographic canonicalization scheme. An ad hoc localeCompare sort is not the property ordering defined by RFC 8785 JSON Canonicalization Scheme, which also specifies primitive serialization and input constraints. For signatures or cross-system content hashes, use the scheme required by the protocol and a conforming implementation. Check numeric and duplicate-key constraints before conversion; sorting cannot restore information a parser already lost.
Handle Unicode as data, not decoration
JSON strings are Unicode text. That is useful for names, languages, and internationalized content, but it also means you should test real data, not only ASCII examples.
{
"name": "Zoë",
"city": "東京",
"message": "Ready 👋"
}Normalize text only when the application has a reason to do so. Do not strip accents, symbols, or non-Latin characters just because a downstream system was not tested properly.
Keep transport encodings explicit
JSON is often embedded in URLs, Base64 strings, forms, logs, or signed payloads. Every extra encoding layer should be intentional.
Use URL Encoder / Decoder for query-string encoding checks, and use Base64 Encoder / Decoder when you need to inspect a Base64-wrapped JSON value.
const encoded = encodeURIComponent(JSON.stringify({ redirect: "/pricing" }))Avoid stacking encodings unless the receiving system requires it. Double-encoded JSON is painful to debug and easy to mishandle.
Debug JSON with a repeatable workflow
Step 1: Confirm the raw bytes are what you expect
Copy the exact payload before any middleware transforms it. Check whether the content is compressed, Base64-wrapped, URL-encoded, or cut off.
Step 2: Validate syntax
Run the payload through a strict JSON parser or JSON Formatter. Fix quotes, commas, brackets, braces, and invalid comments before chasing application logic.
Step 3: Validate the shape
Check required properties, allowed values, array item types, and unexpected fields. Use JSON Schema for contracts shared between teams.
Once the payload is valid, use the JSONPath Tester to test queries against nested values and confirm that each expression selects the intended nodes.
Step 4: Compare expected and actual payloads
Use a diff tool when two payloads look similar. Whitespace, casing, missing fields, and duplicate keys are easier to see in a structured diff.
Step 5: Reproduce the parser environment
Browser JavaScript, Node.js, databases, queues, and third-party SDKs may all parse and serialize differently around edge cases. Reproduce the issue where it actually fails.
Security risks from untrusted JSON
JSON is data, but untrusted data can still be dangerous. Risks include oversized payloads, deeply nested objects, unexpected fields, injection into downstream templates, prototype-pollution bugs in unsafe merge logic, and leaking sensitive data into logs.
Use size limits, depth limits, schema validation, safe merge utilities, redacted logs, and explicit authorization checks. Do not parse unlimited request bodies or log entire payloads when they may contain tokens, addresses, payment data, or personal information.
Large JSON performance considerations
Large payloads can block the main thread in browsers and tie up server resources. If the file is large, ask whether JSON is the right format or whether streaming, pagination, NDJSON, a database export format, or a binary format would be safer.
For browser tools, be mindful of memory usage. Formatting a large file may require holding the original text, parsed object, and formatted output at the same time.
Common JSON mistakes
| Mistake | Why it breaks | Safer approach |
|---|---|---|
| Single quotes | JSON strings require double quotes. | Serialize with JSON.stringify. |
| Trailing commas | Standard JSON rejects them. | Use a formatter before shipping. |
| Comments | Comments are not part of JSON. | Keep notes outside the payload. |
| Duplicate keys | Parser behavior can hide data. | Treat duplicates as invalid. |
| Large numeric IDs | JavaScript can lose precision. | Send exact IDs as strings. |
| Blind parsing | Valid syntax is not valid business data. | Validate schema and permissions. |
| Logging full payloads | JSON can contain private data. | Redact or log only safe fields. |
Sources
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
- ECMA-404: The JSON Data Interchange Syntax
- MDN: JSON
- JSON Schema: Creating your first schema
- JSON Schema: String formats
- RFC 8785: JSON Canonicalization Scheme
- MDN: Request.json() exceptions
Frequently asked questions
Does JSON allow comments?
No. Standard JSON does not allow comments. Some configuration formats extend JSON with comments, but API payloads and standards-based JSON should not rely on that behavior.
Why does valid JavaScript object syntax fail as JSON?
JavaScript object literals allow features JSON does not, including unquoted keys, single-quoted strings, trailing commas, comments, functions, and undefined. JSON is a stricter interchange format.
Should API IDs be numbers or strings in JSON?
Use strings when the identifier must be preserved exactly, especially for large database IDs, payment references, or values that may exceed JavaScript's safe integer range.
What is the difference between formatting and validation?
Formatting changes whitespace and indentation. Validation checks whether syntax, required fields, allowed values, and data types match the expected contract.
Is JSON Schema required for every payload?
No. Small internal payloads may not need a formal schema, but shared APIs, imports, webhooks, and long-lived contracts benefit from schema validation.
Can JSON be dangerous?
JSON itself is a data format, but untrusted JSON can still trigger application bugs, resource exhaustion, unsafe merges, injection into downstream contexts, or accidental logging of sensitive data.
How should I debug a JSON parse error?
Start with the exact raw payload, validate syntax, check encoding layers, compare it with a known-good payload, and then validate the structure against the expected schema.
Should JSON keys be sorted?
Sorting can make diffs easier to read. It is not, by itself, a canonicalization process for signatures or content hashes. Object member order is not part of the JSON data model; follow the serialization rules required by your protocol when exact bytes matter.