GeoPoint类型的对象不可JSON序列化

时间:2019-02-22 19:14:58

标签: python firebase flask firebase-realtime-database flash-message

我想创建一个必须从Firestore中恢复数据并将其公开在json中的API,但是我遇到了以下错误:

Object of type GeoPoint is not JSON serializable

怎么了?这是我的代码:

#!/usr/bin/env python
import firebase_admin
import json
from pprint import pprint as pp
from flask import Flask, flash, request, url_for, jsonify, Response
from firebase_admin import credentials
from firebase_admin import firestore

app = Flask(__name__)

cred = credentials.Certificate('xxxx.json')
firebase_admin.initialize_app(cred)
db = firestore.client()

@app.route('/')
def index():

    markers_ref = db.collection(u'Test')
    docs = markers_ref.get()

    data = []
    for doc in docs:
        data.append(doc.to_dict())

    json_data = json.dumps(data)
    resp = Response(json_data, status=200, mimetype='application/json')

    return resp

if __name__=='__main__':
app.run(debug=True)

1 个答案:

答案 0 :(得分:-1)

以下应该可以解决问题-

from flask import (Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response, jsonify)
import firebase_admin
from firebase_admin import firestore

@app.route('/foods/<id>')
def read_food(id):

    result=FOODS.document(id).get().to_dict()
    record = {}
    # Populate the new dict with JSON serializiable values
    for key in result:
        if isinstance(result[key], firebase_admin.firestore.GeoPoint):
            record[key] =str(result[key].latitude)+','+str(result[key].longitude)
            continue
        record[key] = result[key]

    # Add the key so that we have a reference to the record
    record['key'] = result[key]

    return jsonify(record)