πŸ“¦ Python Tutorial β€” JSON Module

Introduction 🌟

The json module in Python allows you to encode and decode data in theJSON (JavaScript Object Notation) format β€” one of the most popular data formats for APIs, web services, config files, and data interchange.

Note

πŸ’‘ JSON = Lightweight, text-based, language-independent
πŸ’‘ Python provides easy conversion between JSON ↔ Python objects

1. Importing the JSON Module 🧱

import_json.py

import json

2. Converting Python β†’ JSON (Serialization) πŸ“€

Using json.dumps()

dumps_example.py

import json

data = {
    "name": "Sathish",
    "age": 25,
    "languages": ["Python", "Java"]
}

json_str = json.dumps(data)
print(json_str)

βœ” Converts Python dict β†’ JSON string

Pretty Printing JSON

dumps_pretty.py

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

3. Writing JSON to a File πŸ“

json_dump_file.py

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

βœ” dump() writes JSON directly to a file

4. Converting JSON β†’ Python (Deserialization) πŸ“₯

Using json.loads()

loads_example.py

json_str = '{"name":"Sathish","age":25}'
data = json.loads(json_str)
print(data["name"])

Reading JSON from a File

json_load_file.py

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

print(data)

5. Data Conversion Table πŸ”„

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True / Falsetrue / false
Nonenull

6. Handling Custom Objects 🧩

custom_encoder.py

import json

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def encode_user(obj):
    if isinstance(obj, User):
        return {"name": obj.name, "age": obj.age}
    raise TypeError("Object not JSON serializable")

u = User("Sathish", 25)
print(json.dumps(u, default=encode_user))

βœ” Use default= to encode custom classes

7. JSON Decode Hooks πŸͺ

object_hook.py

json_str = '{"name":"Sathish","age":25}'

def to_user(d):
    return User(d["name"], d["age"])

user = json.loads(json_str, object_hook=to_user)
print(user.name, user.age)

βœ” Converts JSON dict β†’ custom class

8. Sorting Keys πŸ”‘

sort_keys.py

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

βœ” Useful for debugging, comparisons, logs

9. Ignoring Invalid Keys (skipkeys=True) 🚫

skipkeys_example.py

print(json.dumps({1: "one", "two": 2}, skipkeys=True))

Note

⚠️ JSON keys must be strings. skipkeys=True silently ignores invalid keys.

10. Real-World Example β€” API Response Handling 🌐

api_example.py

import json

response = '{"status":"ok","data":{"count":5}}'
parsed = json.loads(response)
print(parsed["data"]["count"])

11. Real-World Example β€” Config File Loader βš™οΈ

config_loader.py

import json

with open("config.json") as f:
    config = json.load(f)

print(config["database"]["host"])

βœ” JSON is commonly used for configuration

12. JSON Module Cheat Sheet πŸ“˜

FunctionPurpose
json.dumps()Python β†’ JSON string
json.dump()Python β†’ JSON file
json.loads()JSON string β†’ Python
json.load()JSON file β†’ Python
default=Encode custom objects
object_hook=Decode custom objects
sort_keys=TrueSort keys alphabetically

Best Practices πŸ’‘

  • βœ” Always wrap file operations in with open()
  • βœ” Use JSON for API responses, configs, serialization
  • βœ” Use indent for readable output
  • βœ” Validate JSON before parsing to avoid errors
  • βœ” Use custom encoders for classes

Conclusion πŸŽ‰

>>β€œJSON makes data portable β€” Python makes JSON effortless.” ✨

You now fully understand the JSON module! Want the next topic? Try Pickle, CSV, XML, YAML, REST APIs, or Dataclasses. Just tell me! 😊