Convert search with PyMongo: Dictionary in JSON

0

I'm using PyMongo to do a search:

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

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

    
asked by anonymous 04.12.2014 / 18:21

2 answers

3

The python Standard Library provides the json module, responsible for converting from 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.

    
24.09.2015 / 00:28
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)
    
04.12.2014 / 18:21