🔄 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

MistakeFix It By…
Mixing single & double quotesAlways use double quotes in JSON
Trying to dump non-serializable objectsConvert to serializable types (e.g., str, int, list, etc.)
Writing without closing fileUse with open(...) to auto-close

📝 Summary – Python JSON Cheatsheet

TaskMethodDirection
Python → JSON stringjson.dumps()Serialize
JSON string → Pythonjson.loads()Deserialize
Write to filejson.dump()Serialize
Read from filejson.load()Deserialize
Pretty printindent, sort_keysFormatting

🏁 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