1. What is JSON?

- JSON (JavaScript Object Notation) is a lightweight format for exchanging data.
- Widely used in APIs, configuration files, and web services.
- Looks like a Python dictionary but uses a strict text format.
Example JSON data:
{
"name": "Ali",
"age": 25,
"skills": ["Python", "JavaScript"]
}
2. Working with JSON in Python
Python has a built-in json
module.
import json
3. Converting JSON to Python (Parsing)
import json
# JSON string
data = '{"name": "Ali", "age": 25, "skills": ["Python", "JavaScript"]}'
# Convert JSON → Python dict
person = json.loads(data)
print(person["name"]) # Output: Ali
print(person["skills"]) # Output: ['Python', 'JavaScript']
4. Converting Python to JSON (Serialization)
import json
person = {
"name": "Sara",
"age": 30,
"skills": ["Java", "C++"]
}
# Convert Python → JSON string
json_data = json.dumps(person, indent=4)
print(json_data)
5. Reading and Writing JSON Files
Writing to a JSON file:
import json
person = {"name": "Kamal", "age": 28, "skills": ["Python", "SQL"]}
with open("person.json", "w") as f:
json.dump(person, f, indent=4)
Reading from a JSON file:
with open("person.json", "r") as f:
data = json.load(f)
print(data["name"])
6. Common Use Cases for JSON in Python
Use Case | Example |
---|---|
APIs | Fetching data from web APIs like weather or GitHub |
Config Files | Storing user preferences and app settings |
Data Exchange | Sending structured data between programs |
Databases | Exporting and importing structured data |
7. Example: Working with API Data (GitHub)
import requests
import json
response = requests.get("https://api.github.com/users/octocat")
data = response.json() # directly converts JSON → Python
print("Username:", data["login"])
print("Public Repos:", data["public_repos"])
Summary
- JSON is a text format used for structured data.
- Use
json.loads()
to parse JSON strings → Python objects. - Use
json.dumps()
to convert Python objects → JSON strings. - Use
json.load()
andjson.dump()
for files. - JSON is widely used in APIs, configs, and data exchange.