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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 12 views 0 copies

Python code

28 lines
Python 3.9+
import 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

stdout
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

  1. Use `json.dump` and `json.load` to read/write directly to a file.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.