← Home · Blog

What is JSON — A Complete Guide for Beginners

Published: May 18, 2025 · Last updated: June 20, 2025 · 12 min read · By JSON Suite Team

If you're learning web development, working with APIs, or handling data in any programming language, you'll encounter JSON almost immediately. It's everywhere — and for good reason. This comprehensive guide explains what JSON is, its history, syntax rules, when to use it, security considerations, and how JSON Schema helps validate your data structures.

JSON Stands for JavaScript Object Notation

JSON (pronounced "jay-son") is a text-based format for representing structured data. Despite its name referencing JavaScript, JSON is completely language-independent. Every major programming language — Python, Java, C#, Go, Ruby, PHP, Swift, Kotlin, Rust — can read and write JSON natively or through standard libraries.

The format uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays. Its simplicity and universality have made JSON the dominant data interchange format on the web, surpassing XML in most modern applications.

The History of JSON: From JavaScript to Web Standard

JSON was created by Douglas Crockford in the early 2000s. Crockford, a software architect who later became famous for his book "JavaScript: The Good Parts," noticed that JavaScript's object literal syntax could serve as a lightweight data interchange format. He didn't invent new syntax — he simply recognized that a subset of existing JavaScript notation could be useful for data exchange.

The first JSON specification was published on json.org in 2002. Unlike XML, which required complex parsing and verbose markup, JSON could be parsed directly by JavaScript's eval() function (though this practice is now discouraged for security reasons). This made it incredibly easy for web developers to work with API responses.

JSON's popularity exploded with the rise of AJAX (Asynchronous JavaScript and XML) web applications in the mid-2000s. Despite "XML" being in the acronym, developers quickly discovered that JSON was far more convenient for client-server communication. By 2010, JSON had effectively replaced XML as the default format for REST APIs.

JSON Standards: RFC 8259 and ECMA-404

JSON is defined by two complementary standards that ensure consistent implementation across all platforms:

RFC 8259 (published December 2017) is the IETF standard that defines JSON as an Internet data format. It specifies the grammar, character encoding requirements (UTF-8), and interoperability considerations. RFC 8259 superseded earlier specifications (RFC 4627 and RFC 7159) and is the authoritative reference for JSON implementations.

ECMA-404 (2nd edition, December 2017) is the Ecma International standard that provides a minimal, language-independent description of JSON syntax. While RFC 8259 includes guidance for implementers, ECMA-404 focuses purely on the grammar specification.

Both standards agree on the core syntax but RFC 8259 adds important requirements: JSON text must be encoded in UTF-8, parsers should handle duplicate keys gracefully, and implementations should be prepared for potential interoperability issues with numbers outside IEEE 754 double precision range.

JSON Syntax Rules

JSON has a small set of strict rules that make parsing unambiguous:

  • Data is organized in key-value pairs
  • Keys must be double-quoted strings (no single quotes)
  • Values can be: strings, numbers, booleans (true/false), null, arrays, or objects
  • Objects are wrapped in curly braces {}
  • Arrays are wrapped in square brackets []
  • Items are separated by commas (no trailing comma allowed)
  • No comments are allowed in standard JSON
  • Whitespace (spaces, tabs, newlines) is insignificant outside strings

A Comprehensive JSON Example

{ "name": "Sarah Johnson", "age": 28, "email": "sarah@example.com", "isActive": true, "balance": 1250.75, "middleName": null, "hobbies": ["reading", "coding", "hiking"], "address": { "street": "456 Oak Avenue", "city": "San Francisco", "state": "CA", "zip": "94102", "country": "USA" }, "phoneNumbers": [ {"type": "home", "number": "555-1234"}, {"type": "work", "number": "555-5678"}, {"type": "mobile", "number": "555-9012"} ], "preferences": { "newsletter": true, "notifications": { "email": true, "sms": false, "push": true } } }

This single JSON document demonstrates strings, numbers, booleans, null, arrays, nested objects, and arrays of objects. JSON can represent virtually any data structure by combining these building blocks recursively.

JSON Data Types Explained

TypeExampleNotes
String"hello world"Must use double quotes. Supports Unicode and escape sequences (\n, \t, \", \\, \uXXXX)
Number42, 3.14, -7, 1.5e10Integer or float, scientific notation allowed, no quotes, no leading zeros
Booleantrue, falseLowercase only — True, TRUE, FALSE are invalid
NullnullRepresents empty/missing value, lowercase only
Array[1, 2, 3]Ordered list of values, can be mixed types, can be nested
Object{"key": "value"}Unordered key-value pairs, keys must be unique strings

Note that JSON does not have a native date/time type. Dates are typically represented as ISO 8601 strings (e.g., "2025-05-18T10:30:00Z") or Unix timestamps (e.g., 1716029400).

JSON vs XML: A Detailed Comparison

Before JSON became dominant, XML was the standard for data interchange. Here's how they compare:

AspectJSONXML
SyntaxLightweight, minimal punctuationVerbose with opening/closing tags
Data TypesNative types (string, number, boolean, null, array, object)Everything is text, types via schema
ParsingFast, direct mapping to objectsSlower, requires DOM or SAX parsing
File Size30-50% smaller for equivalent dataLarger due to tag repetition
CommentsNot allowed in standard JSONSupported with <!-- --> syntax
AttributesNo concept of attributesElements can have attributes
NamespacesNot supportedFull namespace support
SchemaJSON Schema (separate standard)XSD, DTD (mature, integrated)
Browser SupportNative JSON.parse(), JSON.stringify()Requires DOMParser
Human ReadabilityExcellent for small documentsBetter for document-like content

JSON wins for API communication and data storage, while XML remains relevant for document formats (DOCX, SVG), enterprise integrations (SOAP), and systems requiring strict schema validation with namespaces.

Where is JSON Used?

  • REST APIs — nearly every modern API sends and receives JSON (Twitter, GitHub, Stripe, etc.)
  • Configuration files — package.json (Node.js), tsconfig.json (TypeScript), settings.json (VS Code)
  • Databases — MongoDB stores documents as BSON (binary JSON), PostgreSQL has JSONB columns, DynamoDB uses JSON
  • Web Storage — localStorage and sessionStorage use JSON strings
  • Data exchange — between microservices, mobile apps, and web clients
  • Webhooks — Stripe, GitHub, Slack, Twilio all send JSON payloads
  • GraphQL — queries return JSON responses
  • Logging — structured logging in JSON format for easy parsing
  • Message Queues — RabbitMQ, Kafka, SQS messages often contain JSON

When NOT to Use JSON

While JSON is versatile, it's not the right choice for every situation:

  • Binary data — JSON is text-based and cannot efficiently represent binary data. Images, videos, and files should use dedicated formats or Base64 encoding (which increases size by ~33%)
  • Streaming data — Standard JSON requires the entire document to be valid, making it unsuitable for streaming. Consider NDJSON (Newline Delimited JSON) or JSON Streaming for continuous data
  • Circular references — JSON cannot represent circular data structures. If object A references object B which references object A, JSON.stringify() will throw an error
  • Very large datasets — For multi-gigabyte data, columnar formats like Parquet or binary formats like Protocol Buffers are more efficient
  • Documents with mixed content — For documents combining text, markup, and metadata (like word processor files), XML or specialized formats work better
  • Type-critical applications — JSON numbers have precision limits (IEEE 754 double). For financial applications requiring exact decimal precision, strings or specialized formats may be safer
  • Configuration needing comments — Standard JSON doesn't support comments. Use JSONC, JSON5, or YAML for commented configuration files

JSON Security Considerations

Working with JSON requires awareness of several security concerns:

JSON Injection

When user input is concatenated into JSON strings without proper escaping, attackers can inject malicious content. Always use proper JSON encoding functions (JSON.stringify() in JavaScript, json.dumps() in Python) rather than string concatenation.

// WRONG - vulnerable to injection const json = '{"name": "' + userInput + '"}'; // CORRECT - properly escaped const json = JSON.stringify({ name: userInput });

Denial of Service (DoS)

Deeply nested JSON structures or extremely large documents can exhaust memory and CPU during parsing. Implement depth limits and maximum size restrictions when accepting JSON from untrusted sources. Most web frameworks allow configuring these limits.

Prototype Pollution (JavaScript)

In JavaScript, carelessly merging JSON data into objects can allow attackers to modify Object.prototype through keys like __proto__ or constructor. Use Object.create(null) for data objects or sanitize keys from untrusted JSON.

// Potentially dangerous - if json contains __proto__ Object.assign(config, JSON.parse(untrustedJson)); // Safer - create object with no prototype const data = Object.assign(Object.create(null), JSON.parse(untrustedJson));

Sensitive Data Exposure

JSON.stringify() will serialize all enumerable properties, potentially exposing sensitive data. Always explicitly select which fields to include in API responses rather than serializing entire objects.

JSON vs JavaScript Objects

While JSON looks like JavaScript object syntax, there are important differences:

  • JSON keys must be quoted — JS objects don't require it
  • JSON doesn't support functions, undefined, Symbol, or BigInt
  • JSON doesn't allow comments
  • JSON doesn't allow trailing commas
  • JSON is always a string — it needs to be parsed into an object
  • JSON strings must use double quotes — JS allows single quotes
  • JSON numbers cannot be NaN, Infinity, or have leading zeros

Working with JSON in Code

JavaScript:

// Parse JSON string → object const data = JSON.parse('{"name": "Alice", "age": 30}'); console.log(data.name); // "Alice" // Convert object → JSON string const json = JSON.stringify(data, null, 2); console.log(json); // formatted JSON // With error handling try { const result = JSON.parse(untrustedInput); } catch (e) { console.error('Invalid JSON:', e.message); }

Python:

import json # Parse JSON string → dictionary data = json.loads('{"name": "Alice", "age": 30}') print(data["name"]) # "Alice" # Convert dictionary → JSON string json_str = json.dumps(data, indent=2) # Read JSON from file with open('data.json', 'r') as f: data = json.load(f) # Write JSON to file with open('output.json', 'w') as f: json.dump(data, f, indent=2)

Introduction to JSON Schema

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It defines the structure, types, and constraints that JSON data must conform to — similar to how XSD works for XML.

Here's a simple example of a JSON Schema:

{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 100 }, "email": { "type": "string", "format": "email" }, "age": { "type": "integer", "minimum": 0, "maximum": 150 }, "hobbies": { "type": "array", "items": { "type": "string" } } }, "required": ["name", "email"] }

JSON Schema enables:

  • Validation — Automatically verify that incoming JSON matches expected structure
  • Documentation — Schema serves as machine-readable API documentation
  • Code generation — Generate TypeScript interfaces, Python classes, or database models from schemas
  • IDE support — Get autocompletion and validation in VS Code, JetBrains IDEs
  • API contracts — Define clear contracts between frontend and backend teams

Learn more in our detailed guide: JSON Schema Explained.

Try It Yourself

Want to practice with JSON? Try our free tools:

  • JSON Formatter — paste JSON and see it beautifully formatted with syntax highlighting
  • JSON Tree Viewer — visualize JSON as an interactive, expandable tree
  • Fix JSON — automatically repair broken JSON with detailed error reports
  • JSON Schema Validator — validate your JSON against a schema
  • JSON Diff — compare two JSON documents and see the differences

More Articles

JSON Tutorial for Beginners — Learn Step by Step

JSON in Multiple Languages — Python, Java, PHP & More

How to Format JSON — A Complete Beginner's Guide

10+ Common JSON Errors and How to Fix Them

JSON vs XML vs YAML — When to Use Which

How to Compare Two JSON Files

JSON Schema Explained