[英]Dumping a pymongo record pretty-printed to text like the mongo shell
我知道我可以打印出像這樣的Mongo記錄:
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ObjectId):
return repr(obj)
else:
return super(CustomJSONEncoder, self).default(obj)
print(json.dumps(obj, cls=CustomJSONEncoder, indent=4, sort_keys=True))
但是我希望輸出看起來像這樣:
"_id" : ObjectId("93768784abd8849385763eab"),
但它看起來像這樣:
"_id" : "ObjectId('93768784abd8849385763eab')",
如果我將repr更改為str,它看起來像這樣:
"_id" : "93768784abd8849385763eab",
在使用pymongo驅動程序時,如何才能使輸出與Mongo shell漂亮的打印機相同或盡可能接近? 注意:這僅用於顯示目的,我不需要將輸出解析回任何東西。
考慮使用標准庫中的pprint模塊:
>>> import pprint
>>> import bson
>>> o = bson.ObjectId()
>>> pprint.pprint({'_id': o})
{'_id': ObjectId('5cc37cfd8b4d4d42dc2cb511')}
pformat可以存儲漂亮格式的結果來替換'
into "
以使結果看起來更像是在Mongo Shell中:
>>> formatted = pprint.pformat({'_id': o})
>>> print(formatted.replace("'", '"'))
{"_id": ObjectId("5cc37cfd8b4d4d42dc2cb511")}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.