What Are Python JSON Operations? See Examples

JSON (JavaScript Object Notation) is a lightweight data format commonly used for data exchange between systems. Python’s json module allows you to parse, serialize, and manipulate JSON data efficiently.

JSON is widely used in web APIs, configuration files, and data storage.

import json

Why JSON Operations Are Important

  • Standard format for data exchange with APIs
  • Simplifies configuration and data storage
  • Easy to read, write, and manipulate in Python
  • Essential for real-world applications like web development and data pipelines

Example 1: Reading JSON Data

import json

json_data = '{"name": "Alice", "age": 25, "city": "New York"}'
data = json.loads(json_data)  # Convert JSON string to Python dict
print(data['name'])  # Output: Alice

Example 2: Writing JSON Data

import json

data = {
    "name": "Bob",
    "age": 30,
    "city": "London"
}

json_string = json.dumps(data)  # Convert Python dict to JSON string
print(json_string)
  • Useful for storing Python objects as JSON for APIs or files

Example 3: Real-World Scenario – Saving Data to a File

import json

users = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30}
]

with open("users.json", "w") as file:
    json.dump(users, file, indent=4)
  • Saves Python objects in a structured JSON file

Example 4: Reading JSON from a File

import json

with open("users.json", "r") as file:
    users = json.load(file)

for user in users:
    print(f"{user['name']} is {user['age']} years old")
  • Reads and parses JSON efficiently for real-world applications

Example 5: Handling JSON from APIs

import json
import requests

response = requests.get("https://api.github.com/users/octocat")
data = response.json()
print(f"User: {data['login']}, ID: {data['id']}")
  • Parsing API responses is common in web development and automation

Best Practices

✔ Use json.load() and json.dump() for files
✔ Use json.loads() and json.dumps() for strings
✔ Use indent for readable JSON formatting
✔ Handle exceptions when parsing JSON from external sources


Conclusion

Python JSON operations are essential for working with structured data. Mastering JSON handling enables you to interact with APIs, manage configuration files, and build data-driven applications effectively.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *