Mongodb正在返回格式化的数据 [英] Mongodb is returning wierdly formatted data

查看:204
本文介绍了Mongodb正在返回格式化的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从我的mongodb数据库中使用 flask-restful pymongo 格式化数据。



例如。

这就是数据库中数据的样子。 >

{_id:ObjectId(5217f3cc7466c06862c4a4f7),Hello:World}



这是从数据库返回时的样子。



{\ _id \:{\$ oid \:\5217f3cc7466c06862c4a4f7\},\Hello \:\World \}

使用此代码:

  def toJSON(data):
返回json.dumps(data,default = json_util.default)



  def get(self,objectid):
collection = db [products]
result = collection.find_one {_id:ObjectId(objectid)})
return toJSON(result)

知道我做错了什么?

解决方案

flask-restful 你在这里返回一个字典而不是 json 。它会自行将字典转换为 json 。所以你的代码看起来应该是这样的:

pre $ def $ get
collection = db [products]
result = collection.find_one({_ id:ObjectId(objectid)})
result ['_ id'] = result ['_ id'] .__ str __()
返回结果

当您返回 json flask-restful 看到并推断它是一个字符串并且转义双引号。


When i try to get this data from my mongodb database using flask-restfuland pymongo i get some wierdly formatted data.

For example.

This is what the data looks like in the database.

{ "_id" : ObjectId("5217f3cc7466c06862c4a4f7"), "Hello" : "World" }

This is what it looks like when it gets returned from the database.

"{\"_id\": {\"$oid\": \"5217f3cc7466c06862c4a4f7\"}, \"Hello\": \"World\"}"

Using this code:

def toJSON(data):
    return json.dumps(data, default=json_util.default)

And this:

def get(self, objectid):
    collection = db["products"]
    result = collection.find_one({"_id": ObjectId(objectid)})
    return toJSON(result)

Anyone know what i'm doing wrong?

解决方案

flask-restful expects you to return a dictionary and not json here. It would convert the dictionary into json on its own. So your code should look like

def get(self, objectid):
    collection = db["products"]
    result = collection.find_one({"_id": ObjectId(objectid)})
    result['_id'] = result['_id'].__str__()
    return result

When you return json flask-restful sees that and infers that it is a string and escapes the double quotes.

这篇关于Mongodb正在返回格式化的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆