JSON validation beyond a missing comma

Separate syntax, duplicate member names, numeric precision and schema requirements when reviewing an API payload.

Valid JSON can still be the wrong data for an application. A parser may accept a payload containing an unexpected type, duplicate member names or a number that loses precision in the receiving language. Syntax validation is the first boundary, followed by schema and business rules.

When an API payload fails, keep the original text and the exact error. Identify whether the problem is malformed JSON, an application contract violation or a value changed during parsing. Reformatting the input before investigation can erase the evidence of duplicate keys or numeric precision loss.

Separate JSON from JavaScript object syntax

The JSON validator uses JavaScript's JSON.parse, reports the root type and structural counts, and can produce formatted output. It validates JSON syntax under that parser, not a custom application schema.

JSON object names and string values use double quotes. Comments, trailing commas and unquoted property names are not ordinary JSON syntax, even though related programming-language formats may accept them. Values such as undefined, NaN and Infinity are also outside JSON's value grammar.

A JSON document can have an array, object, string, number, boolean or null at the root. An API may require an object, but that is an application constraint rather than a universal JSON syntax rule. Keep the parser result and the endpoint's expected root type separate.

{
  "orderId": "9007199254740993",
  "quantity": 2,
  "expedited": false,
  "notes": null
}

This example stores the large identifier as a string so a JavaScript consumer can preserve it exactly. The field types are deliberate; the API contract should explain why each one is used.

Validate types before using values

The number 2 and string "2" are different JSON values. A permissive application can accidentally coerce one into the other, hiding client bugs. Similarly, false, null, an empty string and a missing property have different meanings that should be defined by the schema.

For an order quantity, require the intended numeric type and range. For an identifier, preserve its defined representation rather than converting it to a number just because it contains digits. Leading zeros may be meaningful in a code but disappear under numeric conversion.

Validate nested objects and arrays too. A payload can have the correct root keys while containing an unexpected object where a string was expected deep inside a list. Report the path to the failing field so the caller can correct it.

Three levels of validation
LevelQuestionExample failure
SyntaxCan the text be parsed as JSON?Trailing comma or missing quote
SchemaAre fields, types and ranges permitted?Quantity supplied as an object
Business rulesIs this operation valid now?Ordering an unavailable item
AuthorisationMay this caller perform the operation?Changing another user's order
Resource limitsCan the system process the payload safely?Excessive size or nesting

Do not ignore duplicate member names

JSON's interoperability guidance expects object member names to be unique, but parsers can handle duplicates differently. JavaScript JSON.parse keeps the final value for a repeated name. A formatter then writes only that surviving value, hiding the original duplication.

{"role":"viewer","role":"admin"}

A JavaScript parse of this example retains admin for role. Another system may reject it or behave differently. If a gateway validates one interpretation and an application uses another, the disagreement can become security-relevant.

The local validator reports its JavaScript parsing semantics and does not independently detect every duplicate before parsing. For a protocol that forbids duplicates, use a parser or validation stage that can reject them in the original text. Do not claim a formatted output proves the input had unique names.

Preserve large integers deliberately

JavaScript Number uses a floating-point representation and cannot exactly represent every integer beyond its safe integer range. A JSON number such as 9007199254740993 can lose precision when parsed into that type. The resulting formatted output may differ from the original digits.

For identifiers or exact large values, define a string representation or use a parser and numeric type designed to preserve them. Do not repair the value after it has already rounded, because the original information is gone from the parsed Number.

Money and decimal quantities also need an explicit precision and rounding policy. A JSON number is a textual numeric representation, while each language chooses how to store it. Cross-language agreement requires more than both sides accepting the syntax.

Debug an order ID that changes during formatting

Suppose an API receives a large numeric order ID and later returns a nearby but different number. Preserve the incoming JSON text and compare it with the parsed value. If the language converted it to an inexact floating-point number, the error occurred before the database lookup.

Change the API contract to preserve the identifier in an exact supported form, commonly a string for opaque IDs. Update validation and clients together. Do not simply format the rounded value without decimals; that produces a cleaner-looking wrong identifier.

Add regression cases around the language's exact-integer boundary and include values with leading zeros if the identifier format allows them. Confirm that requests, storage and responses preserve the same intended ID.

Keep arithmetic values separate from identifiers. An order ID usually does not need addition or subtraction, so numeric storage may provide little benefit while introducing precision risk. Choose types according to meaning rather than visual appearance.

Use a schema suited to the API version

A schema can define required fields, allowed types, lengths, ranges and object structure. Decide how unknown properties are handled. Silently accepting misspelled fields can make a client believe an update succeeded when the server ignored the intended value.

Version the contract when meanings change. A field that once accepted a string should not silently become a differently interpreted object without a migration plan. Keep examples tied to the schema version and test representative clients.

Business validation remains separate. A syntactically valid, schema-conforming request can still refer to an unavailable product or an unauthorised account. Apply those checks at the operation boundary and return errors that distinguish the relevant cause without exposing sensitive data.

Bound payload size and nesting

Large or deeply nested input can consume memory and processing time. This browser tool limits text size and applies structural limits to parsed values. A production API also needs request-size and processing controls before and during parsing according to its environment.

Do not assume a post-parse depth check prevents every resource problem, because the parser has already processed the text. Choose streaming or bounded parsing strategies when the workload requires them. Set limits based on realistic payloads and document them for clients.

Test a payload near the allowed boundary and one beyond it. The system should reject excess input clearly and remain responsive. Avoid returning a partial success for a document that was truncated without the caller's knowledge.

Keep formatting separate from byte verification

Pretty-printing changes whitespace and can change member order or numeric representation after parsing. If an HMAC or signature covers the original request bytes, verify those bytes before formatting. A semantically similar document is not necessarily the signed message.

If the protocol uses canonical JSON, follow the specified canonicalisation method exactly. Sorting keys and removing spaces is not a complete substitute for a defined standard with numeric and Unicode rules. Keep test vectors across implementations.

The validator's formatted download is useful for reading and editing supported data, but it is a transformed artifact. Retain the original when investigating signatures, duplicate names or precision-sensitive values.

Treat parsed data as untrusted

Successful JSON parsing does not make strings safe to insert into HTML, SQL or shell commands. Apply the appropriate output and query handling at each later boundary. Parsing also does not authorise the caller to change every field in the object.

Map accepted fields deliberately rather than merging an arbitrary object into sensitive configuration. Review special property names and the behaviour of libraries used for deep merging. The JSON grammar and the receiving object's semantics are different layers.

Frequently asked questions

Can valid JSON contain a top-level number?

Yes. JSON supports several root value types. An API may require an object or array as part of its schema, but that is a separate contract. Read the root-type result and apply the endpoint's documented requirement.

Does the validator check my API schema?

No. It checks syntax through JSON.parse and reports structure. It does not know required fields, allowed ranges or business rules for your service. Use a suitable schema validator and application checks for those requirements.

Why did a duplicate key disappear?

JavaScript parsing keeps the final value for a repeated member name, and formatting writes that parsed object. Preserve the original and use duplicate-aware validation when uniqueness is required. The formatted result cannot reconstruct overwritten values.

Why did a large number change?

The receiving numeric type may not represent it exactly. Use an exact type or a documented string representation before parsing loses precision. Do not assume that all languages preserve every JSON number in the same way.

Can comments be included?

Ordinary JSON does not include comments. Other configuration formats may support them, but they are not interchangeable with a strict JSON API. Use the format expected by the receiver and avoid silently stripping content without a defined process.

Is pretty-printing safe before signature verification?

Not when the signature covers the original bytes. Formatting changes the message representation. Verify the raw body or follow the protocol's explicit canonicalisation method, then parse and display it as needed.

What should a good validation error include?

Identify whether the failure is syntax, schema or an operation rule, and point to the relevant location or field. Preserve user input for correction while avoiding secret values in logs. Clear boundaries make errors easier to fix and safer to handle.

Sources and further reading

50 useful tools · ↑ ↓ to navigate · Enter to open · Esc to close