Export json from Firestore

后端 未结 9 2083
时光取名叫无心
时光取名叫无心 2020-12-14 05:55

As we can download json file at Firebase RTDB console, are there any way to export json file of Firestore collection/document data?

One of my main objectives is to c

9条回答
  •  甜味超标
    2020-12-14 06:31

    If someone wants a solution using Python 2 or 3.

    Edit: note that this does not backup the rules

    Fork it on https://github.com/RobinManoli/python-firebase-admin-firestore-backup

    First install and setup Firebase Admin Python SDK: https://firebase.google.com/docs/admin/setup

    Then install it in your python environment:

    pip install firebase-admin
    

    Install the Firestore module:

    pip install google-cloud-core
    pip install google-cloud-firestore
    

    (from ImportError: Failed to import the Cloud Firestore library for Python)

    Python Code

    # -*- coding: UTF-8 -*-
    
    import firebase_admin
    from firebase_admin import credentials, firestore
    import json
    
    cred = credentials.Certificate('xxxxx-adminsdk-xxxxx-xxxxxxx.json') # from firebase project settings
    default_app = firebase_admin.initialize_app(cred, {
        'databaseURL' : 'https://xxxxx.firebaseio.com'
    })
    
    db = firebase_admin.firestore.client()
    
    # add your collections manually
    collection_names = ['myFirstCollection', 'mySecondCollection']
    collections = dict()
    dict4json = dict()
    n_documents = 0
    
    for collection in collection_names:
        collections[collection] = db.collection(collection).get()
        dict4json[collection] = {}
        for document in collections[collection]:
            docdict = document.to_dict()
            dict4json[collection][document.id] = docdict
            n_documents += 1
    
    jsonfromdict = json.dumps(dict4json)
    
    path_filename = "/mypath/databases/firestore.json"
    print "Downloaded %d collections, %d documents and now writing %d json characters to %s" % ( len(collection_names), n_documents, len(jsonfromdict), path_filename )
    with open(path_filename, 'w') as the_file:
        the_file.write(jsonfromdict)
    

提交回复
热议问题