Convert search with Pymongo: Dictionary in JSON

Asked

Viewed 525 times

0

I’m using Pymongo to make a search:

resultado = db.find_one({'nome':'xpto'})

The result of this search is a Python dictionary, but I need to convert it to a JSON. What’s the best way to do it?

2 answers

3

The python Standard Library provides the module json, responsible for performing the conversion of Dict to json and vice versa.

The code would look like this:

import json
resultado = db.find_one({'nome':'xpto'})
resultadoJson = json.dumps(resultado) #Convertendo dict para json

More information about the json module.

2

Pymongo itself provides a library to handle this situation: bson.json_util

The solution would be as follows:

from bson.json_util import dumps
resultado_json = dumps(resultado)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.