What is JSON?

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It is easy for humans to read and write, and easy for machines to parse and generate. JSON is based on a subset of JavaScript, but it is language-independent and supported by virtually every modern programming language.

JSON Syntax Rules

  • Data is organized in key/value pairs
  • Data is separated by commas
  • Curly braces {} hold objects
  • Square brackets [] hold arrays
  • Keys must be strings (double-quoted)

JSON Data Types

  • String: "Hello World"
  • Number: 42, 3.14
  • Boolean: true, false
  • Null: null
  • Object: {"key": "value"}
  • Array: [1, 2, 3]

Example

{
  "name": "John Doe",
  "age": 30,
  "isActive": true,
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  },
  "hobbies": ["reading", "coding", "gaming"]
}

Common Uses

  • Web APIs: JSON is the standard format for REST API request and response bodies.
  • Configuration files: Many tools use JSON for config (e.g., package.json, tsconfig.json).
  • Data storage: NoSQL databases like MongoDB store data in JSON-like formats.
  • Data interchange: JSON is used to exchange data between client and server.

JSON vs XML

JSON is often preferred over XML because it is more compact, easier to read, and faster to parse. However, XML supports attributes, namespaces, and schemas, making it suitable for more complex document structures.