JSON Module
JSON (JavaScript Object Notation) is one of the most common data formats used for exchanging data over the web, and Python's built-in json module makes it simple to convert between JSON text and native Python objects.
Converting Python to JSON
import json
data = {"name": "Abhay", "course": "Data Science", "active": True}
json_string = json.dumps(data)
print(json_string)
# '{"name": "Abhay", "course": "Data Science", "active": true}'
json.dumps(data, indent=2) # pretty-printed, readable JSON
Converting JSON to Python
import json
json_string = '{"name": "Priya", "score": 92}'
data = json.loads(json_string)
print(data["name"]) # Priya
print(type(data)) #
Reading and Writing JSON Files
import json
# Writing to a file
with open("data.json", "w") as f:
json.dump(data, f)
# Reading from a file
with open("data.json", "r") as f:
loaded_data = json.load(f)
Most web APIs return data in JSON format, so the json module (often paired with the requests library) is essential whenever you're pulling data from an external API for analysis.
Coming Up Next
Next, you'll learn Regular Expressions - a powerful tool for finding and manipulating patterns within text.