First, reference links to other questions I read through. They might be clues to what I am experiencing, although I am not understanding enough yet to see the solution to my problem.
How can I use Python to transform MongoDB's bsondump into JSON?
Unable to deserialize PyMongo ObjectId from JSON
I've got a Flask Restful API I'm working on. An excerpt of my code is as follows:
class DeviceAPI(Resource):
def get(self, deviceID):
# do the query
deviceCollection = db['device']
device = deviceCollection.find_one({'deviceID': deviceID})
print device #1
print ''
print json_util.dumps(device) #2
print ''
s = json_util.dumps(device)
print s #3
print ''
results = {}
results['device'] = s
print results #4
# respond
return results #5
At Print #1, I get the following, and I understand and expect this.
{u'deviceID': u'ABC123', u'_id': ObjectId('....')}
At Print #2 and #3 are identical outputs as expected, and again I understand and expect this (I think).
{"deviceID": "ABC123", "_id": {"$oid": "...."}}
Print #4 has an added key in the dictionary. However, it looks like the value of the key:value is a string where it should be the dictionary as in #2 and #3.
{'device': '{"deviceID": "ABC123", "_id": {"$oid": "...."}}'}
The returned result, #5, according to CURL is along the lines of the following. There are the added / in the there. I suspect because of #4 value looking like a string and that continues in #5 as well.
{"device": "{\"deviceID\": \"ABC123\", \"_id\": {\"$oid\": \"....\"}}"}
I'm trying to get a pure JSON output, not a string representation of the device document. #2 and #3 looked like JSON, but in #4 became a string. Why? And how to do this correctly?