I cannot convert mongodb files to json in python using bson in python

Asked

Viewed 58 times

1

I am trying to work with data from an online database. I am able to do the requisitions in the right way. But when trying to convert the downloaded data using the bson package, I get a string object and not a json. I tried several ways to convert this string to json, but I couldn’t. How do I convert?

Thanks for your help.

from bson.json_util import dumps

.
.
.

dados = colecao.find_one()
ver_json = dumps(dados)
print(ver_json)

>>> '{"_id": {"$oid": "602e6c108a0e449623b9ffd6"}, "cidades": "Maceio", "longitude": 35.5878, "latitude": -9.0, "data": {"$date": 1613617200000}, "temperaturaAr": 25.1, "precipitacao": 2.0, "radiacao": 560.0, "velocidadeVento": 10.0, "direcaoVento": 234.0}'

type(ver_json)
>>> str

3 answers

2

To cast str for a Dict, simply import lib json which is part of the standard python library for JSON Discovery and Code.

The loads function deserializes a string or array of bytes (containing json) for a python object following conversion table.

Conversion table:

JSON Python
Object Dict
array list
string str
number(int) int
number (real) float
true True
false False
null None

Follow an example:

import json
#utilizando o json que forneceu na pergunta
a = '{"_id": {"$oid": "602e6c108a0e449623b9ffd6"}, "cidades": "Maceio", "longitude": 35.5878, "latitude": -9.0, "data": {"$date": 1613617200000}, "temperaturaAr": 25.1, "precipitacao": 2.0, "radiacao": 560.0, "velocidadeVento": 10.0, "direcaoVento": 234.0}'

entidade = json.loads(a)
entidade['_id']
#{'$oid': '602e6c108a0e449623b9ffd6'}
type(entidade)
#<class 'dict'>

1

I have difficulty testing but bson has a direct conversion function. So it should be possible for you to do:

import bson

dados = colecao.find_one()
d = beson.decode(dados)
print(d)                    ## e d seria tipo 'dict'

1


i receive a string object and not a json

Remember that JSON is not a "type", it is only a data format. What the API’s do is map this format to structures proper to each language. In the case of Python, it has already been mentioned conversion table, and in it we see that in your case, a JSON object (delimited by { }) is mapped to a dictionary.

So actually you didn’t need to convert to string. Just use the return from find_one, which is already the dictionary you need (as this dictionary already represents the JSON in question):

dados = colecao.find_one()
print(dados) # imprime o documento
print(type(dados)) # <class 'dict'>

What the another answer suggested it works, of course, but is an unnecessary turn: there’s no reason to turn dados string, then turn this string into dict again. Until because in the end, the generated dictionaries will be equal:

from bson.json_util import dumps
dados = colecao.find_one()
# transforma dados em string
ver_json = dumps(dados)

# transforma a string em dicionário
import json
entidade = json.loads(ver_json)
print(dados == entidade) # True (os dicionários são iguais)

That is, you don’t need any of this. If you want a dictionary, use what was returned by find_one and ready. Use dumps only makes sense if you really need this data in a single string. If you don’t have to, it’s unnecessary to do it all.

Browser other questions tagged

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