将pymongo记录转储精美打印到诸如mongo shell之类的文本

时间:2019-04-26 21:41:57

标签: python mongodb pymongo

我知道我可以打印出Mongo这样的记录:

for (this.format in unique(myDT$strformat)){
  myDT[strformat==this.format, unlist(strsplit(this.format,':')):=tstrsplit(content,':')]
}

但是我希望输出看起来像这样:

by=

但是它看起来像这样:

     <select [(ngModel)]="rejectionReason">
                    <option [ngValue]="undefined" selected disabled>Select</option>
                    <option [value]="one">One</option>
                    <option [value]="Two">Two</option>
                    <option [value]="Three">Three</option>
               </select> 


<button type="button" [disabled]="rejectionReason.length > 0">Submit</button>

如果我将repr更改为str,它看起来像这样:

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))

在使用pymongo驱动程序时,如何获得与Mongo Shell漂亮打印机相同或尽可能接近的输出?注意:这只是出于显示目的,我不需要将输出解析回任何东西。

1 个答案:

答案 0 :(得分:0)

考虑使用标准库中的pprint模块:

>>> import pprint
>>> import bson
>>> o = bson.ObjectId()
>>> pprint.pprint({'_id': o})
{'_id': ObjectId('5cc37cfd8b4d4d42dc2cb511')}

pformat可以存储漂亮格式的结果,以将'替换为",以使结果看起来更像Mongo Shell:

>>> formatted = pprint.pformat({'_id': o})
>>> print(formatted.replace("'", '"'))
{"_id": ObjectId("5cc37cfd8b4d4d42dc2cb511")}
相关问题