Pretty Printing Of Output In Pymongo
Solution 1:
I want to know whether there is any method like
pretty()
in PyMongo
No PyMongo doesn't provide such method. It is only available in the shell.
You need to use the pprint
function from the pprint
module.
Solution 2:
Actually you can also program it by yourself like:
db = connection.[dbname]
collection = db.[yourcollectionname]
for col in collection.find({}):
for keys in col.keys():
print ('{', keys, ":" , col[keys] , '}' )
I think this will be helpful or take it as an option.
Solution 3:
I'm a bit new to this too but I might have found a viable answer for those who are looking. Libraries I'm using are pymongo
, bson
, json
, from bson import json_util
and from bson.json_util import dumps, loads
Where you want to print (or return) try:
print(loads(dumps(stringToPrint, indent=4, default=json_util.default)))
If your data is already using loads, you will not need loads in this statement.
If you want to use return
leave out the first parentheses.
Example:
return json.loads(json.dumps(string, ..... )
If you imported loads and dumps you can leave out json.
.
I haven't tried (because this worked great for me) to alter the 'indent' value but if you don't like how the output looks, try changing that.
Solution 4:
There is no direct method to print output of pymongo in a structured way.
as the output of pymongo is a dict
print(json.dumps('variable with out of pymongo query'))
this will serve your purpose i think
Solution 5:
It probably depends on your IDE, not the pymongo itself. the pymongo is responsible for manipulating data and communicating with the mongodb. I am using Visual Studio with PTVS and I have such options provided from the Visual Studio. The PyCharm is also a good option for IDE that will allow you to watch your code variables and the JSON in a formatted structure.
Post a Comment for "Pretty Printing Of Output In Pymongo"