从 pymongo Flask 验证 Json

Validate Json from pymongo Flask

我正在使用 Flask 和 Mongo 数据库构建 Rest API。

我不确定我使用 pymongo 从 MongoDB 获取的数据是否有效 JSON。

代码

tasks = [
{
    'id': 1,
    'title': u'Buy groceries',
    'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
    'done': False
},
{
    'id': 2,
    'title': u'Learn Python',
    'description': u'Need to find a good Python tutorial on the web',
    'done': False
}
]


@app.route('/tankover/api/v1.0/posts', methods=['GET'])
def post():
    db = connection.posthub
    cursor = dumps(db.post.find())
    return jsonify({'cursor': cursor})

当我对硬编码数据进行 jsonify 显示时,其格式不正确且格式不正确。

输出

{
 "cursor": [
  {
    "description": "Milk, Cheese, Pizza, Fruit, Tylenol", 
    "done": false, 
    "id": 1, 
    "title": "Buy groceries"
  }, 
  {
    "description": "Need to find a good Python tutorial on the web", 
    "done": false, 
    "id": 2, 
    "title": "Learn Python"
  }
 ]
}

但是当我使用数据库中的数据时。我不确定类型和格式。

{
"cursor": "[{\"title\": \"sankit\", \"_id\"
{\"$oid\":\"597619b7c07b2dc30a108def\"}, \"description\": \"hello to 
everyone we are up 
for a great start and moving good\", \"tags\": [\"demo1\", \"demo2\"]}, 
{\"_id\": {\"$oid\": \"59761b2cc6568a4e341b6b89\"}, \"description\": \"lets 
add some thing new\", \"tags\": [\"bonjour\", \"salut\"], \"title\": 
\"hi\"}, 
{\"_id\": {\"$oid\": \"59a5c5f6c6568a0be4447dfb\"}, \"description\": \"okay 
okay okay\", \"tags\": [\"socks\", \"gifts\"], \"title\": \"tinni\"}]"
}

有效且正常吗?

如其中一条评论所述,您已两次调用 dumps。请注意 flask.json.jsonify() 是一个包装 dumps() 的函数。

注意pymongo find() returns一个游标对象不是文件。例如,您可以尝试以下操作:

def post():
    db = connection.posthub 
    documents = [doc for doc in db.post.find({}, {"_id":0})]
    return jsonify({'cursor': documents})

如果您想序列化任何 MongoDB JSON 对象,例如 ObjectIdDate(),您可以使用 bson.json_util 例如:

from bson import json_util 

def post():
    db = connection.posthub 
    documents = [doc for doc in db.post.find({})]
    return json_util.dumps({'cursor': documents})