- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
JSON in Python
JSON (JavaScript Object Notation) is used for storing and exchanging data, commonly in APIs and configuration files.
Python has a built-in module:
import json
Write (Save) JSON to a File
Example Dictionary/Data
data = {
"name": "Deepesh",
"age": 30,
"skills": ["Python", "Selenium", "Automation"]
}
Save to JSON file
import json
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
indent=4 makes the JSON formatted & readable.
Read (Load) JSON from a File
import json
with open("data.json", "r") as file:
content = json.load(file)
print(content)
Output
{'name': 'Deepesh', 'age': 30, 'skills': ['Python', 'Selenium', 'Automation']}
Now content is a Python dictionary, and you can access elements like:
print(content["name"]) print(content["skills"][1])
Convert Python Data ↔ JSON String
Convert Python → JSON string
import json
person = {"city": "Delhi", "pin": 110001}
json_string = json.dumps(person)
print(json_string)
Convert JSON string → Python
import json
json_str = '{"status": "success", "code": 200}'
data = json.loads(json_str)
print(data)
Update JSON File
import json
# Read existing content
with open("data.json", "r") as file:
data = json.load(file)
# Modify data
data["age"] = 31
data["skills"].append("API Testing")
# Write back to file
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Work with Lists in JSON
Example JSON file (employees.json)
[
{"id": 1, "name": "Ankit"},
{"id": 2, "name": "Riya"}
]
Add a new record
import json
with open("employees.json", "r") as file:
employees = json.load(file)
employees.append({"id": 3, "name": "Aman"})
with open("employees.json", "w") as file:
json.dump(employees, file, indent=4)
Summary
| Task | Function |
|---|---|
| Write Python → JSON file | json.dump() |
| Read JSON file → Python | json.load() |
| Python → JSON string | json.dumps() |
| JSON string → Python | json.loads() |