Generating correct JSON string using python
Hi I'm new to python programming. Here I am using dumps to get the output from my mongodb. But in PostMan I am getting invalid JSON string error.
My code:
cursor = db.Details.find()
for document in (yield cursor.to_list(length=100)):
self.write(bson.json_util.dumps(document))
My conclusion:
{"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}}
{"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
{"data": null, "status": "success"}
How I want my result to be:
{"data": [
{"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}},
{"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
], "status": "success"}
Please help me.
Thank you in advance
My screenshot from PostMan
+3
source to share
1 answer
How about you save everything in a list first and then reset 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 a variable success
like your desired output you can 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}))
+2
source to share