Python JSON
JSON (JavaScript Object Notation) is a lightweight data format widely used for APIs, configuration files, and data exchange. Python has a built-in json module that lets you parse JSON strings into Python data structures and convert Python objects back into JSON strings.
1. Parse JSON to Python with json.loads()
Use json.loads() to convert a valid JSON string into a Python dictionary, list, or primitive value:
import json
json_data = '{"name": "Aarav", "age": 22, "skills": ["Python", "SQL"]}'
parsed = json.loads(json_data)
print("Name:", parsed["name"])
print("First Skill:", parsed["skills"][0])
2. Convert Python to JSON with json.dumps()
Use json.dumps() to serialize a Python dictionary or list into a JSON-formatted string, and pass indent to make it human-readable:
import json
course_info = {
"platform": "Expertsjava",
"topic": "Python JSON",
"free": True,
"rating": 4.9
}
pretty_json = json.dumps(course_info, indent=4)
print(pretty_json)
3. Python to JSON Data Type Mapping
When converting Python objects with json.dumps(), Python types map to JSON equivalents automatically:
import json
sample = {
"dict_to_object": {"a": 1},
"list_to_array": [1, 2, 3],
"tuple_to_array": ("x", "y"),
"true_val": True,
"false_val": False,
"none_to_null": None
}
print(json.dumps(sample))
Tip: Use
json.loads() and json.dumps() for strings, and use json.load() and json.dump() when reading from or writing directly to a file.