3

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 enter image description here

Tony Roczz
  • 2,366
  • 6
  • 32
  • 59

1 Answers1

2

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}))
adrianus
  • 3,141
  • 1
  • 22
  • 41
  • Good luck. But you get my vote. Various people have tried to tell the OP the same thing now for days. Add a "success" key and value in the final dict and it should mirror exactly what is asked for. – Blakes Seven Jul 21 '15 at 05:42
  • Ok...? I just noticed the `success` key was missing in my output :) @[tony-roczz](http://stackoverflow.com/users/5039470/tony-roczz) Does this work for you? – adrianus Jul 21 '15 at 05:48
  • @adrianus Thanks for the help it works. My output is as desired. But I am getting this `{"status": "success", "data": null}` additionally. Anyway to solve that – Tony Roczz Jul 21 '15 at 05:49
  • @TonyRoczz I'm sorry, I mistyped (key `success` instead of `status`), could you try again? – adrianus Jul 21 '15 at 05:56
  • @adrianus It works thank you after my output I am getting the `{"status": "success", "data": null}`. Is there way to avoid this. – Tony Roczz Jul 21 '15 at 06:09