What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. It is human-readable and easy to parse, making it a popular choice for web applications, APIs, and configuration files.

1. Why Use JSON?

2. JSON Syntax

JSON consists of:

Example JSON Data

{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com",
  "isEmployed": true,
  "skills": ["JavaScript", "Python", "SQL"],
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zip": "10001"
  }
}

3. JSON Data Types

4. JSON vs JavaScript Object

JSON keys must be in double quotes:

{ "name": "Alice" }

JavaScript objects can have unquoted keys:

{ name: "Alice" }

5. Parsing and Stringifying JSON

In JavaScript

Convert JSON string to object:

let jsonString = '{"name": "John", "age": 30}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John

Convert object to JSON string:

let person = { name: "Alice", age: 25 };
let jsonStr = JSON.stringify(person);
console.log(jsonStr); // Output: {"name":"Alice","age":25}

In Python

Convert JSON string to dictionary:

import json
json_str = '{"name": "John", "age": 30}'
obj = json.loads(json_str)
print(obj["name"])  # Output: John

Convert dictionary to JSON string:

person = {"name": "Alice", "age": 25}
json_str = json.dumps(person)
print(json_str)  # Output: {"name": "Alice", "age": 25}

6. JSON in APIs

JSON is widely used in APIs to exchange data between clients and servers.

Example API Response (JSON)

{
  "status": "success",
  "data": {
    "user": "JohnDoe",
    "id": 12345
  }
}

7. JSON Formatting and Validation

Use online formatters like JSONLint to validate JSON.

Ensure correct syntax: Keys must be strings, and values should be valid data types.

Conclusion

JSON is a powerful, simple, and universal format for data exchange. It’s widely used in web development, APIs, and data storage.