8
How do I convert an object to JSON?
I even found some codes on the internet that even worked, but my object has some fields that are other objects and so the conversion did not reach the last level.
Example:
class Pessoa(object):
codigo = 0
nome = ''
endereco = Endereco()
class Endereco(object):
codigo = 0
logradouro = ''
bairro = ''
cidade = Cidade()
class Cidade(object):
codigo = 0
nome = ''
uf = ''
These are my objects, but doing the conversion I found, the result JSON comes only with the values contained in Person in Addressee, then stay City outside the JSON:
{
'codigo': 1,
'nome': 'Oliveira',
'endereco': {
'codigo': 5,
'logradouro': 'Rua A',
'bairro': 'Campos'
}
}
I mean, I believe the code didn’t go through all the levels.
I’m using the pyMongo and I saw that it has a library bson that has some conversions, but I did not know how to use it or else it does not do what I need.
I’m kind of confused - what are these fields defined in the class? You know that when you define fields like this, they’re static, right? To define object fields, you do inside the
__init__
. Maybe that’s why the object/json conversion methods you experienced aren’t giving you the expected result.– mgibsonbr