JSON

Back

Loading concept...

📦 Python’s JSON Library: Your Magic Translator

Imagine you have a toy box. Inside are LEGO bricks, action figures, and stuffed animals. Now imagine you want to send your friend a list of everything in your toy box through a magic letter. But the letter can only carry words, not actual toys. You need to DESCRIBE your toys in words so your friend can understand what you have!

That’s exactly what JSON does! It turns Python objects (like lists and dictionaries) into text that can be saved or sent anywhere. And when you get that text back, JSON can rebuild your objects from the description!


🎭 The Cast of Characters

Think of JSON like a universal translator between Python and the rest of the world:

Python Object JSON Text
Dictionary {} Object {}
List [] Array []
String "hi" String "hi"
Number 42 Number 42
True/False true/false
None null

🔧 JSON Encoding: Python → Text

Encoding = Taking your Python toys and writing them down as a description.

json.dumps() - Turn Objects into Text

import json

my_pet = {
    "name": "Fluffy",
    "age": 3,
    "is_cute": True
}

text = json.dumps(my_pet)
print(text)
# {"name": "Fluffy", "age": 3, "is_cute": true}

🎯 Notice: Python’s True became true (lowercase). JSON has its own style!

Make It Pretty!

text = json.dumps(my_pet, indent=2)
print(text)

Output:

{
  "name": "Fluffy",
  "age": 3,
  "is_cute": true
}

The indent=2 adds spacing so humans can read it easily!


📖 JSON Decoding: Text → Python

Decoding = Reading a description and rebuilding the actual Python object.

json.loads() - Turn Text Back into Objects

import json

text = '{"name": "Buddy", "age": 5}'

my_dog = json.loads(text)
print(my_dog["name"])  # Buddy
print(my_dog["age"])   # 5

🎯 The magic: That text string became a real Python dictionary you can use!

graph TD A["Python Dict"] -->|json.dumps| B["JSON Text String"] B -->|json.loads| C["Python Dict Again!"] style A fill:#90EE90 style B fill:#87CEEB style C fill:#90EE90

📁 JSON File Operations: Save & Load

Sometimes you want to save your data to a file (like saving a game). JSON makes this super easy!

json.dump() - Save to File

import json

game_save = {
    "player": "Hero123",
    "level": 7,
    "coins": 500
}

with open("save.json", "w") as f:
    json.dump(game_save, f, indent=2)

✅ Now save.json exists on your computer with your data inside!

json.load() - Load from File

import json

with open("save.json", "r") as f:
    loaded_game = json.load(f)

print(loaded_game["level"])  # 7

🧠 Memory Trick

Function What It Does
dump**s** String output
dump Goes to file
load**s** From String
load From file

🎨 Custom JSON Encoding: Special Objects

Here’s a problem: JSON doesn’t know how to handle some Python objects!

from datetime import datetime

data = {"when": datetime.now()}
json.dumps(data)  # ❌ ERROR!

JSON says: “I don’t know what a datetime is!”

Solution: Teach JSON with a Custom Encoder!

import json
from datetime import datetime

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

data = {"when": datetime.now()}
text = json.dumps(data, cls=MyEncoder)
print(text)
# {"when": "2024-01-15T10:30:00"}

🎯 What happened? We taught JSON: “When you see a datetime, turn it into text like this!”

Even Simpler: Using default Parameter

import json
from datetime import datetime

def my_converter(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError("Can't convert!")

data = {"when": datetime.now()}
text = json.dumps(data, default=my_converter)

🎮 Real-World Example: A Mini Address Book

Let’s put it all together!

import json

# Our data
contacts = [
    {"name": "Mom", "phone": "555-1234"},
    {"name": "Best Friend", "phone": "555-5678"}
]

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

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

# Use the data!
for person in loaded:
    print(f"Call {person['name']}: {person['phone']}")

Output:

Call Mom: 555-1234
Call Best Friend: 555-5678

⚡ Quick Reference

graph TD subgraph Encoding A["Python Object"] -->|dumps| B["JSON String"] A -->|dump| C["JSON File"] end subgraph Decoding D["JSON String"] -->|loads| E["Python Object"] F["JSON File"] -->|load| E end style A fill:#FFD700 style E fill:#90EE90 style B fill:#87CEEB style C fill:#DDA0DD style D fill:#87CEEB style F fill:#DDA0DD
Task Function Example
Object → String dumps() json.dumps({"a": 1})
Object → File dump() json.dump(data, file)
String → Object loads() json.loads('{"a": 1}')
File → Object load() json.load(file)
Custom Objects JSONEncoder Use cls= or default=

🚀 You’re Now a JSON Master!

Remember:

  • Encoding = Python → Text (like writing a letter)
  • Decoding = Text → Python (like reading a letter)
  • Files = Use dump/load without the “s”
  • Custom = Teach JSON about special objects with encoders

JSON is everywhere: websites, apps, games, and more. Now you know the magic behind it! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.