【问题标题】:Validate Json from pymongo Flask从 pymongo Flask 验证 Json
【发布时间】:2018-02-27 11:43:10
【问题描述】:

我正在使用 Flask 和 Mongo DB 构建一个 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(),一次使用jsonify()。
  • 如果我只使用 jsonify 它的给出错误: is not JSON serializable 如果我只使用转储它的给出错误:TypeError: 'dict' object is not callable

标签: python json mongodb flask-restful


【解决方案1】:

正如其中一个 cmets 所述,您已经调用了两次 dumps。注意flask.json.jsonify() 是一个包装dumps() 的函数。

注意pymongo find() 返回的是游标对象而不是文档。例如,您可以尝试以下操作:

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

如果您想序列化任何 MongoDB JSON 对象,例如 ObjectId 或 Date(),您可以使用 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})

【讨论】:

  • 我试过了,它给出了一个类型错误:ypeError: ObjectId('597619b7c07b2dc30a108def') is not JSON serializable
  • 我已经更新了上面的答案来回答你的评论。简而言之,你不能序列化任意 Python 对象(不提供编码器/解码器)
  • 它现在工作完美,我现在理解这个概念。谢谢你:)
猜你喜欢
  • 2019-12-03
  • 2020-07-21
  • 2019-11-29
  • 2019-12-10
  • 2015-05-25
  • 2014-08-05
  • 2015-03-30
  • 2016-06-05
  • 2016-11-12
相关资源
最近更新 更多