How to Serialize Chat Messages to a JSON File in Python

Writes a list of chat message dicts to a JSON file with metadata like export time and message count.

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

Python code

26 lines
Python 3.9+
import json
from pathlib import Path
from datetime import datetime

def serialize_messages(messages, output_path):
    data = {
        "exported_at": datetime.now().isoformat(),
        "count": len(messages),
        "messages": messages
    }
    Path(output_path).write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8"
    )
    return output_path

if __name__ == "__main__":
    chat_log = [
        {"user": "alice", "text": "Hello there!", "timestamp": "2024-03-15T10:30:00"},
        {"user": "bob", "text": "Hi alice, how are you?", "timestamp": "2024-03-15T10:31:00"},
        {"user": "alice", "text": "Great, thanks for asking!", "timestamp": "2024-03-15T10:31:30"}
    ]
    
    file_path = serialize_messages(chat_log, "chat_export.json")
    print(f"Messages serialized to {file_path}")
    print(Path(file_path).read_text(encoding="utf-8"))

Output

stdout
Messages serialized to chat_export.json
{
  "exported_at": "2025-01-01T12:00:00.123456",
  "count": 3,
  "messages": [
    {
      "user": "alice",
      "text": "Hello there!",
      "timestamp": "2024-03-15T10:30:00"
    },
    {
      "user": "bob",
      "text": "Hi alice, how are you?",
      "timestamp": "2024-03-15T10:31:00"
    },
    {
      "user": "alice",
      "text": "Great, thanks for asking!",
      "timestamp": "2024-03-15T10:31:30"
    }
  ]
}

How it works

The json.dumps call converts a Python list of dicts into a JSON string with indent=2 for readability and ensure_ascii=False to preserve Unicode characters like emojis. Wrapping it in Path.write_text writes the string to the file with UTF-8 encoding. The function adds metadata (export time and count) to make the file self-describing for later processing. This pattern is common when storing chat conversation snapshots for analysis or model training.

Common mistakes

  • Using `json.dump` instead of `json.dumps` and forgetting to open the file manually
  • Forgetting `ensure_ascii=False` when messages contain non-ASCII characters
  • Not specifying `encoding="utf-8"` causes encoding issues on some platforms

Variations

  1. Use `json.dump` with a file object opened via `with open(output_path, 'w', encoding='utf-8') as f:`
  2. Append messages to an existing JSON file instead of overwriting it

Real-world use cases

  • Exporting chat logs from a support system for QA analysis or training a model.
  • Building a dataset of customer-agent conversations to fine-tune an LLM.
  • Saving conversation history in a debugging tool to reproduce user issues.

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.