How to Convert Python Dict to JSON and Back
Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.
Python code
35 linesimport json
from datetime import datetime, timezone
def convert_data(data, source_format=None, target_format="json"):
"""
Convert Python data structures to txt/json and back.
For beginners: shows how to serialize/deserialize.
"""
if source_format == "json" and target_format == "dict":
return json.loads(data)
if source_format == "dict" and target_format == "json":
return json.dumps(data, indent=2)
if source_format is None and target_format == "json":
return json.dumps(data, indent=2)
raise ValueError("Unsupported conversion")
def add_timestamp():
"""Return current UTC timestamp as ISO string."""
return datetime.now(timezone.utc).isoformat()
if __name__ == "__main__":
sample_dict = {
"name": "PythonBasic",
"level": 1,
"topics": ["variables", "functions", "files"],
"created": add_timestamp()
}
json_text = convert_data(sample_dict, "dict", "json")
print("Converted to JSON:\n", json_text)
print("\nConverted back to dict:")
restored = convert_data(json_text, "json", "dict")
print(restored, type(restored))
Output
Converted to JSON:
{
"name": "PythonBasic",
"level": 1,
"topics": [
"variables",
"functions",
"files"
],
"created": "2024-01-15T12:34:56.789012+00:00"
}
Converted back to dict:
{'name': 'PythonBasic', 'level': 1, 'topics': ['variables', 'functions', 'files'], 'created': '2024-01-15T12:34:56.789012+00:00'} <class 'dict'>
How it works
The json.dumps call serializes a Python dict into a JSON string, using indent=2 for readable formatting. json.loads does the reverse — it parses JSON text back into native Python objects like dicts and lists. The helper uses explicit source/target format checks to make conversions predictable and beginner-friendly. The timestamp is generated in UTC with timezone info so the data stays consistent across cloud services that expect ISO 8601 strings. This pattern is the foundation for exchanging data between Python services and REST APIs or storage systems.
Common mistakes
- Using `json.load` instead of `json.loads` when parsing a JSON string (load reads from a file)
- Forgetting to import `json` before calling the conversion functions
- Passing the data in the wrong order to the helper (source vs target format)
- Assuming all Python types serialize to JSON — tuples become lists and custom objects need a custom encoder
Variations
- Use `json.dumps(data)` without indent for compact output when sending to an API
- Use `pathlib.Path.read_text` plus `json.loads` to read a JSON file from disk
- Add `json.dumps(data, sort_keys=True)` for alphabetically ordered keys
Real-world use cases
- Serializing a Python dict payload before sending it in a POST request to a cloud API.
- Deserializing JSON responses from AWS Lambda or Google Cloud Functions into workable Python dicts.
- Converting job results between JSON files and in-memory dicts in a serverless batch pipeline.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.