How to Safely Export and Migrate Chat Conversation History
Learn how to export conversation history from AI chat platforms on web and mobile, clean the raw export into OpenAI-compatible role/content messages with a Python script, count tokens, redact sensitive data, and verify the migration results. Includes troubleshooting tips for common export and parsing failures.
1. Before Exporting: Know What the File Contains and the Risks
When your session quota runs out, you may no longer be able to send new messages, but the export function usually remains available. This article only covers history records that the platform officially allows you to export; it does not cover bypassing quota limits. Whether a conversation can be continued after migration depends on the target platform’s rules, and this article makes no guarantees.
The exported file is data designed for UI rendering and state restoration, not plain conversation text. It may contain account details, phone numbers, email addresses, API keys embedded in code, customer data, and work content. Before doing anything, take three precautions: back up the original file, process it in an isolated local environment, and redact sensitive content before uploading anything to a third-party platform.
Open the file and inspect the top-level structure first. If the top level is an array, each element usually corresponds to one conversation. If it is an object, common fields include messages or mapping. Field names vary across platforms. This article uses a ChatGPT-style conversations.json as the example; for other platforms, adapt the script to the actual field names.
2. Export Checklist for Web and Mobile
2.1 Web (Desktop)
Follow these steps in order; exact labels depend on the current UI:
- After logging in, click your avatar or account entry in the lower-left corner.
- Go to “Settings” and find “Data controls” or “Data management.”
- Click “Export data.” The platform typically emails a download link to your registered address.
- Download the archive and extract it to get
conversations.json. - Check the file size and modification time to confirm it is not empty or an old file.
2.2 Mobile (iOS)
- Find the export entry in the app’s settings page. Tapping it generates a temporary link.
- Temporary links usually expire quickly, so open the link in Safari as soon as it is generated.
- After downloading, check the “Downloads” folder in the Files app. If the file cannot be saved, verify that the app has file access permission in system settings.
- Copy the file to your computer for further processing.
2.3 Mobile (Android)
- Find the export entry in the app and generate a download link.
- Prefer opening the link in Chrome. System browsers sometimes block non-standard downloads, and switching to Chrome often resolves this.
- After downloading, locate the file in the “Downloads” folder of the file manager.
- Confirm the app has storage write permission; otherwise the file may fail to save.
2.4 Common Errors and Retry Order
When export fails, troubleshoot in the following order instead of repeatedly tapping the generate button:
- Confirm the file is not empty and not a previous export.
- If the link has expired, regenerate it.
- Try a different browser, especially on mobile.
- Switch to web export.
- If it still fails, contact the platform’s official support channels with your app version and device model.
3. Field Mapping, Cleaning Script, and Output Structure
3.1 Target Structure
Mainstream OpenAI-compatible APIs accept an array of objects, each containing role and content. The goal of cleaning is to convert the platform’s raw structure into this format while removing metadata such as timestamps, rendering states, and retry markers.
3.2 Field Mapping Table (ChatGPT-Style Export)
| Source field | Meaning | Target field | Handling |
|---|---|---|---|
| mapping | Message tree keyed by node ID | None | Trace back from current_node along parent to the root |
| message.author.role | Role | role | Keep only user and assistant |
| message.content.parts | List of text fragments | content | Keep only string fragments, join and trim whitespace |
| content.content_type | Content type | None | Process only text; skip images, attachment placeholders, etc. |
| Empty message or parts | System placeholder node | None | Skip |
| Consecutive duplicates with same role | Duplicate submission or generation | None | Deduplicate |
| create_time, etc. | Timestamps | None | Delete |
If the export is a linear array (e.g., a messages list), the script automatically falls back to linear traversal with the same mapping rules.
3.3 Complete Cleaning Script
The script keeps only the branch containing current_node, so other branches discarded by regeneration are dropped. If you want to keep all branches, modify the traversal logic yourself.
Save as clean_export.py:
import jsonimport sysfrom pathlib import PathALLOWED_ROLES = {"user", "assistant"}MAX_DEPTH = 5000def extract_text(content):"""Extract plain text from a content object; skip non-text types."""if not isinstance(content, dict):return ""if content.get("content_type", "text") != "text":return ""parts = content.get("parts") or []texts = [p.strip() for p in parts if isinstance(p, str) and p.strip()]return "\n".join(texts)def get_text(msg):content = msg.get("content")if isinstance(content, str):return content.strip()return extract_text(content)def get_role(msg):author = msg.get("author")if isinstance(author, dict):return author.get("role", "")return msg.get("role", "")def walk_branch(mapping, current_node):"""Trace from current_node up to the root via parent, returning nodes in chronological order."""chain, seen = [], set()node_id = current_nodewhile node_id:if node_id in seen:print(f"Warning: circular reference at node {node_id}; traceback interrupted", file=sys.stderr)breakif len(chain) >= MAX_DEPTH:print("Warning: branch depth exceeds limit; traceback interrupted", file=sys.stderr)breaknode = mapping.get(node_id)if node is None:print(f"Warning: parent node {node_id} not found; traceback ended early", file=sys.stderr)breakseen.add(node_id)chain.append(node)node_id = node.get("parent")return list(reversed(chain))def clean_conversation(conv):mapping = conv.get("mapping")current = conv.get("current_node")if isinstance(mapping, dict) and current:raw = [n.get("message") for n in walk_branch(mapping, current)]else:# Fallback: used when the export is a linear messages listraw = conv.get("messages") or []messages = []for msg in raw:if not isinstance(msg, dict):continuerole = get_role(msg)if role not in ALLOWED_ROLES:continuetext = get_text(msg)if not text:continueitem = {"role": role, "content": text}if messages and messages[-1] == item:continuemessages.append(item)return messagesdef normalize_top_level(data):"""Support three top-level shapes: conversation array, object with conversations, single conversation object."""if isinstance(data, list):return dataif isinstance(data, dict):if isinstance(data.get("conversations"), list):return data["conversations"]if "mapping" in data or "messages" in data:return [data]raise SystemExit("Unrecognized top-level structure: expected a conversation array, or an object containing mapping/messages.")def check_results(results):problems = []for conv in results:msgs = conv["messages"]for i, m in enumerate(msgs):if not m["content"]:problems.append(f"{conv['title']}: message {i} has empty content")for i in range(1, len(msgs)):if msgs[i]["role"] == msgs[i - 1]["role"]:problems.append(f"{conv['title']}: message {i} has the same role as the previous one ({msgs[i]['role']}); please review manually")return problemsdef process_export(input_path, output_path):src, dst = Path(input_path), Path(output_path)try:with src.open("r", encoding="utf-8") as f:data = json.load(f)except FileNotFoundError:raise SystemExit(f"Input file not found: {src}")except json.JSONDecodeError as e:raise SystemExit(f"JSON parse failed (line {e.lineno}, column {e.colno}): {e.msg}. ""Make sure the file is complete and not truncated.")except OSError as e:raise SystemExit(f"Cannot read file: {e}")results = []for index, conv in enumerate(normalize_top_level(data), start=1):if not isinstance(conv, dict):continuemessages = clean_conversation(conv)if messages:results.append({"title": conv.get("title") or f"Conversation {index}","messages": messages,})if not results:raise SystemExit("No messages extracted. Check whether the field names match the mapping table.")for problem in check_results(results):print("Validation note: " + problem, file=sys.stderr)tmp = dst.with_name(dst.name + ".tmp")try:with tmp.open("w", encoding="utf-8") as f:json.dump(results, f, ensure_ascii=False, indent=2)tmp.replace(dst)except OSError as e:raise SystemExit(f"Write failed: {e}")total = sum(len(c["messages"]) for c in results)print(f"Done: {len(results)} conversations, {total} messages in total, written to {dst}")if __name__ == "__main__":if len(sys.argv) != 3:raise SystemExit("Usage: python clean_export.py input.json output.json")process_export(sys.argv[1], sys.argv[2])
Example usage:
python clean_export.py conversations.json cleaned.json
The script writes results via a temporary file followed by a rename. If writing fails midway, the original output file is not corrupted.
3.4 Cleaned Output Structure
The output is an array where each element represents one conversation. In the example below, a duplicated user message has already been deduplicated:
[{"title": "Weekly report drafting","messages": [{"role": "user", "content": "Help me draft a weekly report template."},{"role": "assistant", "content": "Sure, here is the template:\n1. Completed this week\n2. Risks and blockers\n3. Plan for next week"}]}]
When migrating to another API, simply extract the messages array of the desired conversation.
4. Backup, Token Counting, Redaction, and Migration Verification
4.1 Back Up Before Migrating
Before cleaning, keep the original file and record its checksum. This way you can return to the raw data if cleaning goes wrong.
Linux or macOS:
cp conversations.json conversations.backup.jsonshasum -a 256 conversations.json > conversations.sha256
Windows PowerShell:
Copy-Item conversations.json conversations.backup.jsonGet-FileHash conversations.json -Algorithm SHA256 | Out-File conversations.sha256
The backup file contains the same sensitive content, so store it on an encrypted disk or in a controlled directory—not in a public folder of a shared cloud drive.
4.2 Token Counting
Token counts determine whether the migrated content fits within the target model’s context window. The following function uses tiktoken when available; otherwise it falls back to a rough character-based estimate for scale assessment only:
import jsonimport sysdef estimate_tokens(text):try:import tiktokenexcept ImportError:return max(1, len(text) // 2) # Rough estimate, used when tiktoken is not installedenc = tiktoken.get_encoding("o200k_base")return len(enc.encode(text))def count_tokens(path):with open(path, "r", encoding="utf-8") as f:data = json.load(f)for conv in data:total = sum(estimate_tokens(m["content"]) for m in conv["messages"])print(f"{conv['title']}: ~{total} tokens, {len(conv['messages'])} messages")if __name__ == "__main__":count_tokens(sys.argv[1])
Estimates are only for judging scale. Before the actual migration, verify with the target platform’s tokenizer or the usage data returned by its API.
4.3 Redaction
The cleaned file may still contain sensitive information. The following rules handle common formats but cannot cover names, addresses, or internal company codenames:
import jsonimport reimport sysREDACT_RULES = [(re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "[EMAIL]"),(re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)"), "[PHONE]"),(re.compile(r"(?<!\d)\d{17}[\dXx](?!\d)"), "[ID NUMBER]"),(re.compile(r"\b(?:sk|pk|ak)-[A-Za-z0-9_-]{16,}\b"), "[API KEY]"),]def redact(text):for pattern, label in REDACT_RULES:text = pattern.sub(label, text)return textdef redact_file(src, dst):with open(src, "r", encoding="utf-8") as f:data = json.load(f)for conv in data:for m in conv["messages"]:m["content"] = redact(m["content"])with open(dst, "w", encoding="utf-8") as f:json.dump(data, f, ensure_ascii=False, indent=2)if __name__ == "__main__":redact_file(sys.argv[1], sys.argv[2])
Usage:
python redact.py cleaned.json cleaned_redacted.json
The redaction script is only a first-pass filter. Before uploading, still perform manual spot checks, focusing on names, company names, customer names, addresses, and internal links.
4.4 Spot Checks Before Migration
- Randomly sample three to five conversations and verify each message against the original export for completeness.
- Check that the role sequence is normal. The script flags consecutive identical roles; if there are many such warnings, investigate branch handling or field mapping.
- Compare total message counts with the effective messages in the original file. Large discrepancies may indicate dropped branches.
- Confirm there is no empty content or garbled text. Garbled characters usually mean the original file is not UTF-8 encoded.
- Confirm the redacted file contains no residual accounts, keys, or personal information.
5. Troubleshooting Checklist
| Symptom | Possible cause | Resolution |
|---|---|---|
| Exported file is empty or abnormally sized | Export incomplete or download interrupted | Re-export; verify file size and timestamp |
| File is an old export | A file with the same name already exists in Downloads | Confirm the old file is backed up before deleting, then re-download |
| Temporary link returns an error | Link expired | Regenerate the link and open it promptly |
| Browser does not start downloading | System browser blocks non-standard downloads | Retry with Chrome or Safari |
| iOS file cannot be saved | App lacks file access permission | Check permissions in system settings, then re-download |
| Android download fails | Missing storage write permission | Grant the permission and retry |
| JSON parse failure reported | File truncated or corrupted | Re-export; do not manually edit the original file |
| No messages extracted | Top-level structure or field names differ from the mapping table | Open the file, inspect field names, and adjust the script accordingly |
| Message count is significantly low | current_node points to a short branch, or branches were dropped | Confirm the current branch is the one you need; switch to full-branch traversal if necessary |
| Non-ASCII text appears garbled | File encoding is not UTF-8 | Open with a UTF-8-capable editor or use an encoding conversion tool |
| Sensitive data remains after redaction | Regex rules do not cover that format | Add rules and perform manual spot checks |
If you cannot resolve an issue, keep the original backup and error output, then work through the table item by item. Never modify or overwrite the original export file without a backup.
After migration, delete local temporary files and intermediate results, keeping only the final redacted version. Store the original backup according to your own data retention requirements, and delete it yourself when it is no longer needed.
