๐ Python and JSON: A Beginner-Friendly Guide
JSON (JavaScript Object Notation) is one of the most popular formats for storing and transferring data. Whether you're working on APIs, web apps, or data files, Python makes working with JSON easy and powerful.
๐ What is JSON?
JSON is a lightweight, human-readable format to represent structured data as key-value pairs. It’s widely used in APIs and configurations.
Example of JSON:
{
"name": "Alice",
"age": 25,
"languages": ["Python", "JavaScript"]
}
๐ฆ Working with JSON in Python
Python has a built-in module called json
that lets you encode and decode JSON data.
๐ Importing the JSON Module
import json
1️⃣ Converting Python to JSON (Serialization)
Use json.dumps()
to convert a Python object into a JSON string.
import json
data = {
"name": "Alice",
"age": 25,
"languages": ["Python", "JavaScript"]
}
json_string = json.dumps(data)
print(json_string)
๐ Output:
{"name": "Alice", "age": 25, "languages": ["Python", "JavaScript"]}
๐ก Tip:
To write JSON to a file:
with open("data.json", "w") as file:
json.dump(data, file)
2️⃣ Converting JSON to Python (Deserialization)
Use json.loads()
to convert a JSON string into a Python object.
json_data = '{"name": "Alice", "age": 25, "languages": ["Python", "JavaScript"]}'
data = json.loads(json_data)
print(data["name"]) # Alice
๐️ To read from a file:
with open("data.json", "r") as file:
data = json.load(file)
print(data)
๐ง Common Use Cases
-
๐ APIs: Receiving/sending data to web servers
-
๐งพ Config files: Storing app settings
-
๐พ Data storage: Saving structured data locally
✅ Best Practices
-
Always validate JSON data before using it
-
Use
try-except
blocks to handle errors while reading JSON -
Use
indent
injson.dumps()
for pretty-printing:print(json.dumps(data, indent=4))
๐งช Quick Example: Parsing API Response
import json
import requests
response = requests.get("https://api.github.com/users/octocat")
data = response.json() # Converts JSON response to Python dict
print(data["login"]) # octocat
๐ฏ Conclusion
Python makes it easy to handle JSON — a skill every programmer should master. Whether you're building APIs, working with web data, or managing configs, knowing how to read and write JSON in Python is essential.
No comments:
Post a Comment