Jay Prakash Thakur
Jay Prakash Thakur

Reputation: 615

creating a nested json document

I have below document in mongodb.

enter image description here

I am using below python code to save it in .json file.

file = 'employee'
json_cur = find_document(file)
count_document = emp_collection.count_documents({})

with open(file_path, 'w') as f:
     f.write('[')
     for i, document in enumerate(json_cur, 1):
         print("document : ", document)
         f.write(dumps(document))
         if i != count_document:
              f.write(',')
     f.write(']')

the output is -

{

    "_id":{
        "$oid":"611288c262c5c14df84f649b"
    },
    "Lname":"Borg",
    "Fname":"James",
    "Dname":"Headquarters",
    "Projects":"[{"HOURS": 5.0, "PNAME": "Reorganization", "PNUMBER": 20}]"

}

enter image description here

But i need it like this (Projects value without quotes) -

{

    "_id":{
        "$oid":"611288c262c5c14df84f649b"
    },
    "Lname":"Borg",
    "Fname":"James",
    "Dname":"Headquarters",
    "Projects":[{"HOURS": 5.0, "PNAME": "Reorganization", "PNUMBER": 20}]

}

Could anyone please help me to resolve this?

Thanks,

Jay

Upvotes: 0

Views: 43

Answers (1)

Jonatan Orozco
Jonatan Orozco

Reputation: 103

You should parse the JSON from the Projects field

Like this:

from json import loads
document['Projects'] = loads(document['Projects'])

So,

file = 'employee'
json_cur = find_document(file)
count_document = emp_collection.count_documents({})

with open(file_path, 'w') as f:
     f.write('[')
     for i, document in enumerate(json_cur, 1):
         document['Projects'] = loads(document['Projects'])
         print("document : ", document)
         f.write(dumps(document))
         if i != count_document:
              f.write(',')
     f.write(']')

Upvotes: 1

Related Questions