Mongodb is returning wierdly formatted data

2019-08-18 16:50发布

问题:

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?

回答1:

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.



回答2:

No, that's supposed to be like that.

MongoDB uses BSON, which extends JSON with some extra types, such as ObjectId. To represent those in JSON, you get the weird-looking $oid and friends.

The backslashes are most likely added by some tool to allow for quotes inside of a String literal (which is enclosed by quotes). Unless you are somehow double-encoding things.