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

1

1 Answer 1

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}))
Sign up to request clarification or add additional context in comments.

5 Comments

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.
Ok...? I just noticed the success key was missing in my output :) @tony-roczz Does this work for you?
@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
@TonyRoczz I'm sorry, I mistyped (key success instead of status), could you try again?
@adrianus It works thank you after my output I am getting the {"status": "success", "data": null}. Is there way to avoid this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.