π Python and JSON β Easily Work with Data Like a Pro | TechTown.in
In todayβs world of APIs, data sharing, and web development, one format rules them all β JSON (JavaScript Object Notation).
Itβs lightweight, human-readable, and Python makes it super easy to work with JSON using the built-in json module.
In this article, youβll learn how to parse, convert, read, write, and handle JSON data using Python β with examples that just make sense.
π§ What is JSON?
JSON (JavaScript Object Notation) is a popular format used for storing and exchanging data, especially in APIs and web apps.
It looks like a Python dictionary, but with a slightly different syntax:
{
"name": "Tanmay",
"age": 23,
"city": "Jaipur"
}
π¦ Importing the JSON Module
import json
β Now you can convert between Python objects and JSON strings.
π Convert Python to JSON β json.dumps()
import json
data = {"name": "Tanmay", "age": 23, "city": "Jaipur"}
json_string = json.dumps(data)
print(json_string)
π― Output:
{"name": "Tanmay", "age": 23, "city": "Jaipur"}
β This is now a JSON-formatted string β ready to send via API, save to file, etc.
π Convert JSON to Python β json.loads()
json_data = '{"name": "Tanmay", "age": 23, "city": "Jaipur"}'
parsed = json.loads(json_data)
print(parsed["city"]) # Output: Jaipur
π― Converts string β Python dict.
π Write JSON to File β json.dump()
data = {"product": "Laptop", "price": 55000}
with open("data.json", "w") as f:
json.dump(data, f)
β This saves the Python object to a file in JSON format.
π Read JSON from File β json.load()
with open("data.json", "r") as f:
content = json.load(f)
print(content["product"])
π― Reads file β Python dictionary.
π Real-World Use Case β API Response Parsing
Imagine receiving this JSON from a weather API:
{
"location": "Delhi",
"temp": 34,
"condition": "Sunny"
}
You can parse it like this:
response = '{"location": "Delhi", "temp": 34, "condition": "Sunny"}'
weather = json.loads(response)
print(f"Weather in {weather['location']}: {weather['temp']}Β°C, {weather['condition']}")
π§ͺ Bonus: Formatting JSON Output
Pretty Print with indent
print(json.dumps(data, indent=4))
Sorted Keys
print(json.dumps(data, indent=2, sort_keys=True))
π« Common Pitfalls
| Mistake | Fix It By… |
|---|---|
| Mixing single & double quotes | Always use double quotes in JSON |
| Trying to dump non-serializable objects | Convert to serializable types (e.g., str, int, list, etc.) |
| Writing without closing file | Use with open(...) to auto-close |
π Summary β Python JSON Cheatsheet
| Task | Method | Direction |
|---|---|---|
| Python β JSON string | json.dumps() | Serialize |
| JSON string β Python | json.loads() | Deserialize |
| Write to file | json.dump() | Serialize |
| Read from file | json.load() | Deserialize |
| Pretty print | indent, sort_keys | Formatting |
π Final Thoughts
Pythonβs json module makes it incredibly easy to send, receive, and store data β especially when working with APIs, web apps, or config files.
Whether you’re a beginner or a pro, learning how to use JSON in Python is a must-have skill for modern development.
π Keep mastering practical Python at TechTown.in