How to Convert Data to JSON and Back in Python
Convert a Python dict into a JSON string with indentation, then parse it back into a dict, demonstrating a common round-trip conversion for beginners.
Python code
28 linesimport json
from datetime import datetime
def convert_data(data):
"""Convert a dict into a JSON string and back to dict."""
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)
return json_str, parsed
def main():
sample_data = {
"user": "alice",
"message": "hello",
"timestamp": datetime.now().isoformat(),
"metadata": {"source": "chat", "version": 1}
}
json_output, parsed_data = convert_data(sample_data)
print("Original type:", type(sample_data).__name__)
print("JSON string type:", type(json_output).__name__)
print("Parsed back type:", type(parsed_data).__name__)
print("JSON output:")
print(json_output)
print("Round-trip equality:", sample_data == parsed_data)
if __name__ == "__main__":
main()
Output
Original type: dict
JSON string type: str
Parsed back type: dict
JSON output:
{
"user": "alice",
"message": "hello",
"timestamp": "2025-03-31T10:15:30.123456",
"metadata": {
"source": "chat",
"version": 1
}
}
Round-trip equality: True
How it works
The json.dumps call serializes a Python dict into a JSON string, using indent=2 for readability. json.loads then deserializes that string back into a Python dict. This round-trip pattern is foundational for exchanging data with APIs, LLMs, and files. The equality check returns True because both the original dict and parsed dict have the same content, despite the JSON string being textual.
Common mistakes
- Confusing `json.dumps` (dict to string) with `json.loads` (string to dict).
- Forgetting that datetime objects are not JSON serializable by default.
- Assuming the round-trip preserves object types that are not native JSON types.
Variations
- Use `json.dump` and `json.load` to read/write directly to a file.
- Add a custom encoder to handle datetime objects automatically.
Real-world use cases
- Preparing structured data to send in an LLM API request payload.
- Parsing the JSON response from an AI model into Python objects for further processing.
- Storing conversation history as JSON in a database or cache for chatbot applications.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.