Lesson 20: Working with JSON in Python

๐ŸŽฏ Lesson Objective

To learn how to read, write, and manipulate JSON data in Python using the built-in json module.


๐Ÿงฉ 1. What Is JSON?

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data.

  • It is text-based and human-readable.
  • Supports objects (dict), arrays (list), strings, numbers, booleans, and null.

โœ… Example JSON

{
    "name": "Sameer",
    "age": 25,
    "skills": ["Python", "Excel", "Web Scraping"]
}

โš™๏ธ 2. Importing the JSON Module

import json

๐Ÿ”„ 3. Converting Python to JSON (Serialization)

  • Use json.dumps() to convert Python objects to JSON string.
data = {"name": "Sameer", "age": 25, "skills": ["Python", "Excel"]}
json_str = json.dumps(data)
print(json_str)

Output:

{"name": "Sameer", "age": 25, "skills": ["Python", "Excel"]}
  • Save JSON to a file using json.dump():
with open("data.json", "w") as f:
    json.dump(data, f)

๐Ÿงฐ 4. Converting JSON to Python (Deserialization)

  • Load JSON string to Python dict:
json_str = '{"name": "Sameer", "age": 25, "skills": ["Python", "Excel"]}'
data = json.loads(json_str)
print(data["name"])

Output:

Sameer
  • Load JSON from a file:
with open("data.json", "r") as f:
    data = json.load(f)
print(data["skills"])

Output:

['Python', 'Excel']

๐Ÿงฑ 5. Working with Nested JSON

nested_json = {
    "person": {
        "name": "Ali",
        "age": 22,
        "address": {"city": "Warangal", "country": "India"}
    }
}

# Access nested data
print(nested_json["person"]["address"]["city"])

Output:

Warangal

๐Ÿ”„ 6. Pretty Printing JSON

print(json.dumps(data, indent=4))

Output:

{
    "name": "Sameer",
    "age": 25,
    "skills": [
        "Python",
        "Excel"
    ]
}

๐Ÿ› ๏ธ 7. Updating JSON Data

data["age"] = 26
data["skills"].append("Web Scraping")

with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

๐ŸŒ 8. Real-Life Example โ€“ Storing Contact Book

contacts = {
    "Ali": {"phone": "9876543210", "email": "ali@example.com"},
    "Sara": {"phone": "9123456789", "email": "sara@example.com"}
}

# Save to file
with open("contacts.json", "w") as f:
    json.dump(contacts, f, indent=4)

# Load from file
with open("contacts.json", "r") as f:
    data = json.load(f)

print(data["Sara"]["phone"])

Output:

9123456789

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *