Day 36/100: Working with JSON in Python
 Rahul Gupta

Rahul Gupta @therahul_gupta

About: I am Software Engineer

Joined:
Jun 5, 2022

Day 36/100: Working with JSON in Python

Publish Date: Jul 23
1 0

Welcome to Day 36 of your Python learning journey!
Today, we dive into a real-world skill: working with JSON data in Python.
JSON (JavaScript Object Notation) is everywhere—APIs, config files, databases, and web apps use it to store and exchange data.

Let’s learn how to read, write, parse, and manipulate JSON in Python with ease! 🧠


📦 What is JSON?

JSON is a lightweight data format similar to Python dictionaries and lists.

Example JSON:

{
  "name": "Alice",
  "age": 30,
  "skills": ["Python", "Data Science"]
}
Enter fullscreen mode Exit fullscreen mode

📚 Python's json Module

Python provides a built-in module named json to handle JSON data.

import json
Enter fullscreen mode Exit fullscreen mode

📥 Converting JSON to Python (Deserialization)

You can load JSON strings into Python dictionaries using json.loads().

import json

json_str = '{"name": "Alice", "age": 30, "skills": ["Python", "Data Science"]}'
data = json.loads(json_str)

print(data["name"])  # Output: Alice
print(type(data))    # <class 'dict'>
Enter fullscreen mode Exit fullscreen mode

📤 Converting Python to JSON (Serialization)

You can convert Python objects (dict, list, etc.) into JSON strings using json.dumps().

person = {
    "name": "Bob",
    "age": 25,
    "skills": ["JavaScript", "React"]
}

json_data = json.dumps(person)
print(json_data)
Enter fullscreen mode Exit fullscreen mode

📝 Pretty Printing JSON

You can format JSON output with indentation for better readability:

print(json.dumps(person, indent=2))
Enter fullscreen mode Exit fullscreen mode

📁 Reading JSON from a File

with open('data.json', 'r') as file:
    data = json.load(file)

print(data["name"])
Enter fullscreen mode Exit fullscreen mode

💾 Writing JSON to a File

with open('output.json', 'w') as file:
    json.dump(person, file, indent=4)
Enter fullscreen mode Exit fullscreen mode

🔁 JSON and Python Data Types

JSON Python
Object dict
Array list
String str
Number int/float
true/false True / False
null None

🧨 Handling Errors

When working with JSON, handle decoding errors using try-except.

try:
    data = json.loads('{"name": "Alice", "age": }')  # Invalid JSON
except json.JSONDecodeError as e:
    print("Error parsing JSON:", e)
Enter fullscreen mode Exit fullscreen mode

✅ Practical Use Case: Fetching API Data

import requests
import json

response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()

for user in users:
    print(user['name'], '-', user['email'])
Enter fullscreen mode Exit fullscreen mode

🛠️ Summary

  • Use json.loads() to parse JSON strings.
  • Use json.dumps() to create JSON strings from Python data.
  • Use json.load() and json.dump() to work with JSON files.
  • JSON is used widely in APIs, config files, and more.

Comments 0 total

    Add comment