Reputation: 2398
Hi I am new to python programming. Here I use dumps to get the output from my mongodb. But I get a malformed JSON string error in PostMan.
My Code is:
cursor = db.Details.find()
for document in (yield cursor.to_list(length=100)):
self.write(bson.json_util.dumps(document))
My output is:
{"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}}
{"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
{"data": null, "status": "success"}
How I want my output to be:
{"data": [
{"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}},
{"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
], "status": "success"}
Please help me.
Thanks in advance
My Output screenshot from PostMan
Upvotes: 3
Views: 98
Reputation: 3199
How about you first save everything in a list and then dump that list to json
?
data = []
cursor = db.Details.find()
for document in (yield cursor.to_list(length=100)):
data.append(document)
self.write(bson.json_util.dumps({"data": data}))
Edit:
For getting the success
variable like your desired output, you could try
data = []
status = ""
cursor = db.Details.find()
for document in (yield cursor.to_list(length=100)):
if 'status' in document: # check if key 'status' in document
status = document[status]
else:
data.append(document)
self.write(bson.json_util.dumps({"data": data, "status": status}))
Upvotes: 2