Skip to content

JSON Best Practices: Formatting, Validation, and API Design

JSON is the lingua franca of the modern web. This guide covers formatting conventions, schema validation, RESTful API design patterns, and how JSON compares to XML and YAML — all grounded in the official RFC 8259 specification.

By Guangming ChenUpdated 2026-08-01

What is JSON?

JSON (JavaScript Object Notation) defined in RFC 8259 is a lightweight, text-based, language-independent data interchange format. It was derived from JavaScript object literal syntax, but it is not a strict subset of JavaScript. JSON represents structured data using two universal structures — name/value pairs (objects) and ordered lists (arrays) — that map directly to the data structures of virtually every modern programming language.

JSON was originally specified by Douglas Crockford and later standardized by the IETF in RFC 8259. The format is intentionally minimal: it has no comments, no trailing commas, no single-quoted strings, and a single numeric type called "number." This minimalism is what makes JSON both trivial to parse and easy for humans to read.

Today JSON is the de facto standard for RESTful APIs, NoSQL document stores (such as MongoDB and CouchDB), configuration files (package.json, tsconfig.json), and structured logging. Understanding its rules is essential for any developer working on the web.

JSON Structure and Data Types

RFC 8259 defines exactly six data types. Every JSON value is one of: string, number, boolean, null, object, or array. There are no dates, no binaries, no integers vs floats, and no undefined. Knowing this constraint is the first step toward writing correct JSON.

  • String: Double-quoted Unicode text. Escape sequences like \n, \t, and \uXXXX are supported. Single quotes are not valid.
  • Number: A single IEEE 754 double-precision style value. There is no separate integer type — large integers above 253-1 may lose precision in JavaScript runtimes.
  • Boolean: The literal tokens true and false. Quoted versions are strings, not booleans.
  • Null: The literal token null represents the absence of a value. It is not the same as an empty string, zero, or undefined.
  • Object: An unordered collection of name/value pairs wrapped in braces { }. Keys must be strings.
  • Array: An ordered list of values wrapped in brackets [ ]. Values can be of mixed types.

Formatting conventions that keep JSON maintainable: use 2-space indentation, keep keys in camelCase, never include trailing commas, and prefer nullover empty strings to express "no value."

Schema Validation

JSON Schema provides a standardized way to annotate and validate JSON documents. Defined by the JSON Schema Specification, it lets you describe the expected structure, data types, required fields, value ranges, and constraints of a JSON object. Schema validation is critical for APIs because it catches malformed input at the boundary, prevents runtime errors downstream, and serves as living documentation for both producers and consumers of data.

A schema document is itself JSON. The current draft is 2020-12. The most useful keywords to know are:

  • type: Restricts the value to one of the six JSON types.
  • required: An array of property names that must be present.
  • properties: Defines the schema for each object key.
  • items: Defines the schema for array elements.
  • format: Annotates strings with semantics like date-time, email, or uri.
  • additionalProperties: false: Forbids unknown keys — useful for catching typos in API clients.

Best practice: validate on both the server (to protect your data store) and the client (to give users fast feedback). Libraries such as ajv (JavaScript), jsonschema (Python), and gojsonschema (Go) implement the standard and run in milliseconds.

API Design Best Practices

RESTful API design with JSON requires consistent conventions for resource naming, status codes, error envelopes, and pagination. A well-designed JSON API treats the response body as a contract: every field has a stable type, every error has a machine-readable code, and every collection supports pagination so clients can reason about the data without surprises.

Conventions that scale across teams and languages:

  • Use nouns, not verbs, in paths: /users/42 instead of /getUser?id=42. The HTTP method expresses the verb.
  • Be consistent with casing: Pick camelCase or snake_case for the entire API and never mix them inside one response.
  • Wrap errors in a stable envelope: Always return { "error": { "code": "...", "message": "..." } } with a meaningful HTTP status code (4xx for client errors, 5xx for server errors).
  • Paginate every list endpoint: Use cursor or offset/limit and return a next_cursor so the client can fetch the next page.
  • Use ISO 8601 strings for dates: "2026-07-29T10:30:00Z" is unambiguous across time zones. Never use epoch numbers as JSON numbers — they exceed safe integer precision beyond 253-1.
  • Version your API: Prefix paths with /v1/ so breaking changes ship as /v2/ without breaking existing clients.

A common mistake is returning different shapes for the same resource depending on context. If /users/42 returns a User object, every other endpoint that includes a user should embed the same User shape. Predictable shapes make client SDKs trivial to write.

JSON vs XML Comparison

Compared to XML, JSON offers a smaller payload, faster parsing, and a data model that maps directly to most programming languages. XML excels at document-centric data with mixed content, attributes, namespaces, and stylesheets (XSLT). For pure data interchange over HTTP — the dominant case in modern APIs — JSON is the right default and is what RFC 8259 was designed to enable.

XML requires a parser that understands opening tags, closing tags, attributes, CDATA sections, and namespaces. JSON requires only two structural tokens (braces and brackets) plus six value types. The result: a typical JSON payload is 20–40% smaller than the equivalent XML and parses in a fraction of the time.

That said, XML still wins in domains that need schema-validated documents (XSD), styling (XSLT), or mixed content like prose with embedded markup. SOAP services, Office Open XML (.docx), and SVG are all XML for good reason. Choose the tool that fits the job.

Comparison Table: JSON vs XML vs YAML

AspectJSONXMLYAML
Syntax styleKey-value pairs and arraysTags with attributes and nested elementsIndentation-based structure
File sizeCompact (no tags)Largest (verbose tags)Smallest (no braces or quotes)
Parsing speedFast (native in most languages)Slower (DOM/SAX parsing)Slower (indentation parsing)
CommentsNot allowed by RFC 8259Supported (<!-- -->)Supported (# style)
Data types6 types: string, number, boolean, null, object, arrayAll data is text; types inferredRich: includes dates, nulls, anchors
Best use caseAPIs, web data exchange, configDocuments, SOAP, enterprise schemasConfiguration files, CI/CD pipelines
StandardRFC 8259W3C XML 1.0YAML 1.2
Human readabilityGood (but no comments)Good (but verbose)Excellent (cleanest)

Technical Reference: RFC 8259

RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format is the authoritative specification for JSON. It obsoletes RFC 7159 and RFC 4627. Key points every developer should know:

  • Encoding: JSON text shall be encoded in UTF-8 by default. Earlier RFCs allowed UTF-16 and UTF-32; RFC 8259 mandates UTF-8 for interoperability.
  • No comments: JSON does not permit comments. Configuration tools that allow comments (JSON5, JSON-C) are using non-standard extensions.
  • Unique keys: Object key names SHOULD be unique. When duplicates exist, parsers receive all values but only the last value is reachable — behavior is implementation-defined.
  • Number precision: Numbers are syntactically unlimited, but implementations that store them as IEEE 754 doubles cannot represent integers larger than 253-1 exactly.
  • Top-level value: A JSON text is a single serialized value — it may be an object or array, but it may also be a bare string, number, boolean, or null.

For validation vocabulary, the companion standard is the JSON Schema Specification, currently at draft 2020-12. Together, RFC 8259 and JSON Schema form the foundation of every modern JSON API.

Frequently Asked Questions

What is JSON and what is it used for?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format defined in RFC 8259. It is used to represent structured data using human-readable key-value pairs and arrays. JSON is language-independent and is the de facto standard for data exchange between web servers and clients, configuration files, and NoSQL databases.

What is JSON Schema and why is it important?

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the expected structure, data types, required fields, value ranges, and constraints of a JSON object. Schema validation is critical for APIs because it catches malformed input at the boundary, prevents runtime errors, and serves as living documentation for both producers and consumers of data.

Should JSON API responses use camelCase or snake_case?

Both are valid, but consistency is what matters. Most JavaScript ecosystems prefer camelCase because it matches native JS conventions, while Python backends often default to snake_case. The best practice is to pick one style per API, document it explicitly, and never mix the two within the same response. Many teams use camelCase on the wire and translate at the framework boundary.

What is the difference between JSON and XML?

JSON is a lightweight, key-value-based format designed for data interchange, while XML is a markup language that supports attributes, namespaces, and mixed content. JSON is smaller on the wire, faster to parse, and maps directly to most programming language data structures. XML is heavier but better suited for document-centric data that needs validation (XSD) or styling (XSLT). For most modern APIs, JSON is the preferred format.

Related Tools