Início/Blog/What is a JSON format? The Definitive Guide to Syntax, Types, Examples & Best Practices
Developer Guide2026-10-16•15 min read

What is a JSON format? The Definitive Guide to Syntax, Types, Examples & Best Practices

What is a JSON format? Learn what JSON stands for, how it works, the 6 core data types, strict syntax rules, common parsing errors, and code examples in JavaScript & Python.

OCC

Online Case Convertor Team

Editorial & Tech Research Team

QUICK ANSWER

What is a JSON Format in 30 Seconds?

JSON stands for JavaScript Object Notation. It is a lightweight, text-based, open-standard file and data interchange format used to store and exchange structured data between software applications, web browsers, mobile apps, and backend servers.

Despite having "JavaScript" in its name, JSON is completely language-independent. Virtually every modern programming language — including Python, Java, C#, Go, Rust, PHP, Ruby, and C++ — includes native, high-speed libraries to read (parse) and generate (serialize) JSON data.

File Extension .json
MIME Media Type application/json
Official Spec RFC 8259 / ECMA-404
Primary Role APIs & Configurations

Need to check or beautify your JSON right now? Use our free, 100% private Online JSON Formatter & Minifier to validate syntax, format messy payloads, and compress data locally in your browser.

Why Did JSON Take Over the Internet?

In the early days of web services (late 1990s and early 2000s), data was exchanged primarily using XML (eXtensible Markup Language) and heavyweight protocols like SOAP. While XML was powerful, it was notoriously verbose, difficult to parse, and created massive overhead for mobile devices and lightweight web browsers.

In 2001, programmer Douglas Crockford specified JSON. He realized that JavaScript already had an elegant, compact syntax for representing objects and lists. By formalizing this syntax into a strict, minimal specification, JSON solved the biggest pain points of digital data exchange:

×

The Old Way: Verbose XML

<user id="101">
  <name>Sarah Connor</name>
  <role>Admin</role>
  <skills>
    <skill>Security</skill>
    <skill>Ops</skill>
  </skills>
</user>

Requires opening and closing tags for every single attribute. Heavy payload size and complex DOM parser requirements.

✓

The Modern Way: Clean JSON

{
  "id": 101,
  "name": "Sarah Connor",
  "role": "Admin",
  "skills": ["Security", "Ops"]
}

Zero redundant tags. Clean key-value pairs that directly mirror native dictionaries, hash maps, and arrays in memory.

Today, JSON powers virtually every REST API, GraphQL query result, webhook notification, mobile application backend, and modern configuration file (such as package.json and tsconfig.json).

Visual Anatomy of a JSON Document

Every JSON document is built from two universal structural collections: Objects (enclosed in curly braces) and Arrays (enclosed in square brackets).

developer-profile.json
Standard JSON Format
{
  "username": "alex_dev",             // String (double quotes)
  "reputationScore": 4850,              // Number (integer)
  "hourlyRate": 95.50,                 // Number (floating-point)
  "isAvailableForHire": true,          // Boolean (true or false)
  "secondaryEmail": null,               // Null (empty value)
  "primarySkills": [                   // Array (ordered list)
    "TypeScript",
    "Node.js",
    "PostgreSQL"
  ],
  "location": {                        // Nested Object
    "city": "San Francisco",
    "state": "California",
    "postalCode": "94107"
  }
}

{ } Curly Braces

Wrap an Object. Encapsulate an unordered set of name/value pairs.

[ ] Square Brackets

Wrap an Array. Encapsulate an ordered sequence of zero or more values.

: Colon

Separates the key from its corresponding value in an object.

, Comma

Separates pairs in objects and elements in arrays. Never place a comma after the final item!

The 6 Core JSON Data Types (In Depth)

Unlike complex programming languages with dozens of primitive types, JSON keeps its specification intentionally minimal. It supports exactly 6 data types — no more, no less:

1 String

Text

A sequence of zero or more Unicode characters. Must be wrapped in double quotes ("..."). Supports backslash escapes like , , ", and A.

"message": "Hello, world! Welcome to JSON."

✗ 'message': 'Single quotes are invalid'

2 Number

Numeric

Standard double-precision 64-bit floating point numbers. Can be integers (42), decimals (3.1415), negative (-17), or exponential (2.5e4).

"temperature": -4.5, "speed": 1.2e3

✗ "val": 012 (No leading zeros, NaN, or Infinity)

3 Boolean

Logical

Represents truth values. Must be written strictly in lowercase as either true or false.

"isActive": true, "isArchived": false

✗ "flag": True (Capitalized letters are invalid)

4 Null

Absence

Represents an intentional empty, non-existent, or unassigned value. Written in lowercase as null.

"deletedAt": null

✗ "deletedAt": undefined (undefined does not exist in JSON)

5 Object

Dictionary

An unordered collection of zero or more key/value pairs enclosed in curly braces { }. Keys must be string literals in double quotes.

{ "theme": "dark", "fontSize": 14 }

✗ { theme: 'dark' } (Unquoted keys are invalid)

6 Array

List

An ordered collection of values enclosed in square brackets [ ]. Can hold any valid JSON types, including nested objects and arrays.

[ "alpha", "beta", 100, true, null ]

✗ [ "a", "b", ] (Trailing comma throws SyntaxError)

Crucial Distinction: What JSON Can NEVER Contain

Because JSON is a pure data transport format and not an execution environment, the following are strictly prohibited in standard JSON:

  • × Functions or methods (cannot serialize code)
  • × Comments (no // or /* */)
  • × undefined (must use null)
  • × Native Date objects (must use ISO-8601 strings)
  • × Regular expressions (e.g. /abc/i)
  • × Circular references (causes infinite recursion)

The 7 Deadly JSON Syntax Sins (And How to Fix Them)

Over 90% of all JSON parsing failures (SyntaxError: Unexpected token) are caused by just seven simple oversights. Review these mistakes to write bulletproof JSON:

1 The Trailing Comma Trap (The #1 Culprit)

SyntaxError

In modern JavaScript, trailing commas in objects and arrays are allowed and even encouraged by linters. In standard JSON, a comma after the final property or item is an instant parse failure.

✗ Broken (Trailing Comma):

{
  "name": "Atlas",
  "version": "2.0",
}

✓ Fixed (No Trailing Comma):

{
  "name": "Atlas",
  "version": "2.0"
}

2 Single Quotes Instead of Double Quotes

SyntaxError

Python and JavaScript developers frequently use single quotes for strings. In JSON, single quotes are completely illegal for both keys and string values.

✗ Broken (Single Quotes):

{
  'status': 'operational'
}

✓ Fixed (Double Quotes):

{
  "status": "operational"
}

3 Unquoted Keys in Objects

SyntaxError

In JavaScript, writing { port: 8080 } is standard object notation. In JSON, every single key MUST be wrapped in double quotes.

✗ Broken (Bare Key):

{ port: 8080 }

✓ Fixed (Quoted Key):

{ "port": 8080 }

4 Adding Comments (// or /* */)

SyntaxError

Douglas Crockford deliberately removed comments from JSON so that developers wouldn't use comments to hold parsing instructions (which destroyed interoperability in early XML).

✗ Broken (Commented):

{
  // Server environment
  "env": "production"
}

✓ Fixed (No Comment / Key Workaround):

{
  "_comment": "Server environment",
  "env": "production"
}
5 Leading Zeros

"code": 042 is invalid. Use string "042" or standard number 42.

6 Unescaped Quotes

"He said "Hi"" breaks. Always escape internal quotes: "He said "Hi"".

7 NaN / Undefined

NaN and undefined are illegal. Always substitute with null.

JSON vs. Other Formats: The Ultimate Comparison

How does JSON stack up against other industry data formats? Here is how to choose the right format for your project:

Format Human Readability Payload Overhead Parsing Speed Best For
JSON High Low Very Fast Web APIs, Webhooks, Single Page Apps, Configs
YAML Very High Very Low Moderate DevOps, Docker Compose, Kubernetes, GitHub Actions
XML Moderate Heavy (Closing tags) Moderate Legacy SOAP, Banking, SVG Graphics, Android Layouts
CSV High (Simple) Minimal Instant Tabular spreadsheets, Flat records (No nested data)
Protocol Buffers None (Binary) Ultra Minimal Blazing Fast Internal gRPC Microservices, High-throughput systems

The Verdict: If you are building a public API or transferring data between a server and a frontend web browser, JSON remains the undisputed #1 choice due to its zero-configuration universal support and balance of human readability with machine performance.

How to Work with JSON in Code

Here is how to parse and generate JSON in the world's two most popular programming languages:

JavaScript / TypeScript Browser & Node.js
// 1. Parsing: Convert JSON string into a JavaScript Object
const jsonText = '{"title": "Deep Work", "pages": 304, "isRead": true}';

try {
  const book = JSON.parse(jsonText);
  console.log(book.title); // Output: "Deep Work"
} catch (err) {
  console.error("Invalid JSON syntax:", err.message);
}

// 2. Serialization: Convert JavaScript Object into formatted JSON string
const newBook = {
  title: "Atomic Habits",
  author: "James Clear",
  tags: ["self-help", "productivity"]
};

// Pass 'null' for replacer, and '2' for readable 2-space indentation
const formattedJson = JSON.stringify(newBook, null, 2);
console.log(formattedJson);
Python Using the built-in json module
import json

# 1. Parsing: Convert JSON string into a Python Dictionary
raw_json = '{"server": "prod-01", "uptime_hours": 142.8, "active": true}'
data = json.loads(raw_json)
print(data["server"])  # Output: prod-01

# 2. Serialization: Convert Dictionary into pretty-printed JSON string
user_payload = {
    "username": "tejas_j",
    "roles": ["editor", "developer"],
    "verified": True
}

# indent=2 formats the output, sort_keys=True sorts keys alphabetically
json_output = json.dumps(user_payload, indent=2, sort_keys=True)
print(json_output)

Advanced JSON in Modern Software Engineering

Beyond basic API responses, JSON has evolved into several specialized formats you will encounter in enterprise systems:

A JSON Schema

A standard vocabulary that allows you to annotate and validate the structure, constraints, and data types of your JSON documents. It acts as an automated contract between frontend and backend teams.

B JSON-LD (Linked Data)

Used for SEO and Semantic Web data. Embedded directly into web pages inside <script type="application/ld+json"> tags so search engines like Google can display rich search snippets and FAQs.

C JSON Lines (JSONL / NDJSON)

A streamable format where each line is an independent, valid JSON document. Widely used for big data pipelines, AI model training datasets (OpenAI, HuggingFace), and real-time server log files.

JSON Minification vs. Prettification: What's the Difference?

Prettified JSON includes line breaks and space indentation (typically 2 or 4 spaces) so developers can easily read and debug data. However, spaces and carriage returns take up unnecessary bytes. Minified JSON strips out all non-essential whitespace, reducing payload size by 25% to 45%. Production APIs and CDNs always serve minified JSON to save network bandwidth and boost load speeds.

★

How to Validate & Format JSON Safely (Zero Privacy Risk)

Developers constantly need to inspect API responses, fix syntax errors, or minify payloads for production. However, pasting proprietary JSON data, API keys, or customer records into random third-party web formatters is a massive security hazard because many tools upload your text to their servers.

To solve this, we created the Online JSON Formatter & Minifier. It is 100% client-side, running purely in your browser's local memory using native ECMA-404 parsing engines. No data ever leaves your device.

How to Use It in 3 Simple Steps:

  1. Paste your raw or minified JSON into the input box on the JSON Formatter tool.
  2. Choose your action — Click "Format (2 Spaces)" or "Minify". The tool validates syntax instantly, pointing to the exact line and character if an error exists.
  3. Copy or Download — Click "Copy to Clipboard" or download the cleaned file as a valid .json file with one click.

Frequently Asked Questions About JSON

What does JSON stand for?

JSON stands for JavaScript Object Notation. It was designed in 2001 by Douglas Crockford based on a subset of the JavaScript programming language (ECMA-262 3rd Edition), but is completely language-independent.

Can I use single quotes in a JSON file?

No. The official JSON standard (RFC 8259) strictly requires double quotes ("...") for both keys and string values. Single quotes ('...') will cause all standard JSON parsers to throw a syntax error.

Does JSON support comments?

No, pure JSON does not support comments (// or /* */). If you need comments in configuration files, consider using JSONC (JSON with Comments, used in VS Code) or YAML.

How do I store dates and timestamps in JSON?

JSON does not have a native Date type. The universally accepted industry standard is to format dates as ISO 8601 strings in UTC, such as "2026-10-16T12:00:00Z", or as Unix epoch timestamps in milliseconds (1760616000000).

Can a JSON document start with an array instead of an object?

Yes! Under modern RFC 8259 specifications, a valid JSON document can have any valid JSON value as its top-level root element. While most documents root in an Object ({ }), rooting in an Array ([ ]) is completely valid and common for bulk data APIs.

What is the difference between JSON and a JavaScript Object?

A JavaScript Object is an in-memory data structure in JavaScript that can contain functions, undefined, Symbols, unquoted keys, and single-quoted strings. JSON is a strict textual string format with restricted syntax rules (double-quoted keys, no functions, no comments) designed for machine storage and transmission.

How do I fix "Unexpected token in JSON at position X"?

This error means your JSON string violates the RFC 8259 specification at the specified character offset. The most frequent causes are trailing commas, unquoted keys, single quotes, or unescaped characters. Paste your payload into our JSON Formatter to locate the exact syntax break instantly.

What is the maximum size of a JSON file?

The JSON specification itself imposes no file size limit. The only limits are the memory capacity (RAM) and parser buffer limits of the software reading the file. For multi-gigabyte datasets, streaming formats like JSON Lines (JSONL) are recommended over one giant JSON array.

Master Your JSON Workflows Today

Understanding JSON is one of the most fundamental skills in modern software engineering, web development, and digital marketing. Its simplicity, speed, and universal language support make it the undisputed backbone of the connected web.

Whether you are building REST APIs, inspecting webhook payloads, or standardizing configuration files, keep your syntax clean, validate regularly, and protect your data privacy.

OCC

Online Case Convertor Team

The Online Case Convertor editorial team creates in-depth technical guides, formatting tutorials, and developer toolkits to help professionals and developers write cleaner, properly-cased text faster.