如何通过Python代码将Firebase Firestore数据库导出为JSON格式?(无谷歌账号权限场景)
Got it, let's walk through how to export your Firestore database to JSON using your existing service account credentials. We'll handle nested collections, Firestore-specific data types, and preserve document IDs so you can recreate an identical database later.
Step 1: Set Up the Firestore Connection
First, let's formalize your existing connection code into a standalone script, adding a check to avoid reinitializing the Firebase app multiple times:
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import json # Load your service account credentials (paste your actual JSON values here) service_account_cert = { "type": "service_account", "project_id": "...", "private_key_id": "...", "private_key": "-----BEGIN PRIVATE KEY-----\n ...", "client_email": "...@appspot.gserviceaccount.com", "client_id": "...", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/...gserviceaccount.com" } # Initialize Firebase app only once if not firebase_admin._apps: cred = credentials.Certificate(service_account_cert) firebase_admin.initialize_app(cred) # Get Firestore client db = firestore.client()
Step 2: Recursively Fetch All Data (Including Subcollections)
Firestore uses a nested collection-document structure, so we need a recursive function to capture every layer. We'll also convert Firestore-specific data types (like Timestamp or GeoPoint) into JSON-serializable formats:
def convert_firestore_value(value): """Convert Firestore-native types to JSON-friendly formats""" if isinstance(value, firestore.Timestamp): return value.to_datetime().isoformat() elif isinstance(value, firestore.GeoPoint): return {"latitude": value.latitude, "longitude": value.longitude} elif isinstance(value, dict): return {k: convert_firestore_value(v) for k, v in value.items()} elif isinstance(value, list): return [convert_firestore_value(item) for item in value] else: return value def fetch_collection(collection_ref): """Recursively pull all documents and subcollections from a collection""" collection_data = {} # Fetch all documents in the current collection docs = collection_ref.stream() for doc in docs: doc_data = convert_firestore_value(doc.to_dict()) # Save the document ID to recreate it later doc_data["__doc_id__"] = doc.id # Fetch and process all subcollections for this document subcollections = doc.reference.collections() subcollection_data = {} for subcol in subcollections: subcollection_data[subcol.id] = fetch_collection(subcol) if subcollection_data: doc_data["__subcollections__"] = subcollection_data collection_data[doc.id] = doc_data return collection_data # Fetch all top-level collections in the database exported_data = {} top_level_collections = db.collections() for col in top_level_collections: exported_data[col.id] = fetch_collection(col)
Step 3: Save the Export to a JSON File
Finally, write the collected data to a JSON file with readable formatting:
with open("firestore_full_export.json", "w", encoding="utf-8") as export_file: json.dump(exported_data, export_file, indent=2, ensure_ascii=False) print("Success! Database exported to firestore_full_export.json")
Key Details to Note:
- We store document IDs in
__doc_id__so you can recreate documents with the exact same IDs in your new database. - Subcollections are grouped under
__subcollections__to preserve the original nested structure. - Firestore-specific types are converted to JSON-compatible values—you'll need to reverse this conversion when importing to your new database (e.g., turn ISO strings back into
Timestampobjects).
内容的提问来源于stack exchange,提问作者SadDeveloepr

