|
| 1 | +import firebase_admin |
| 2 | +from firebase_admin import credentials |
| 3 | +from firebase_admin import firestore |
| 4 | +import json |
| 5 | + |
| 6 | +key_file = "../credentials.json" |
| 7 | +cred = credentials.Certificate(key_file) |
| 8 | +firebase_admin.initialize_app(cred) |
| 9 | + |
| 10 | +db = firestore.client() |
| 11 | + |
| 12 | +# @thanks https://stackoverflow.com/a/57561744/811306 |
| 13 | +def set(my_dict, field_path, value): |
| 14 | + """Given `foo`, 'key1.key2.key3', 'something', set foo['key1']['key2']['key3'] = 'something'""" |
| 15 | + here = my_dict |
| 16 | + keys = field_path.split('.') |
| 17 | + for key in keys[:-1]: |
| 18 | + # Create key with empty dictionary if it does not exist and move pointer. |
| 19 | + here = here.setdefault(key, {}) |
| 20 | + here[keys[-1]] = value |
| 21 | + |
| 22 | +# for collection in [{id: 'dayplans'}]: |
| 23 | +for collection in db.collections(): |
| 24 | + collection_name = collection.id |
| 25 | + print(f"Exporting {collection_name}...") |
| 26 | + json_file = collection_name + '.json' |
| 27 | + |
| 28 | + # documents = db.collection(collection_name).recursive().limit(100).get() |
| 29 | + documents = db.collection(collection_name).recursive().get() |
| 30 | + data = {} |
| 31 | + for doc in documents: |
| 32 | + print(doc.reference.path) |
| 33 | + keys = doc.reference.path.split('/')[1:] |
| 34 | + key = '.'.join(keys) |
| 35 | + set(data, key, doc.to_dict()) |
| 36 | + |
| 37 | + # print(json.dumps(data, indent=2, default=str)) |
| 38 | + |
| 39 | + with open(json_file, 'w') as file: |
| 40 | + json.dump(data, file, indent=4, sort_keys=True, default=str, ensure_ascii=False) |
| 41 | + |
| 42 | + print(f"☑️ Exported to {json_file}.") |
0 commit comments