jazzband / jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
http://jsonmodels.readthedocs.org/en/latest/
BSD 3-Clause "New" or "Revised" License
335 stars 51 forks source link

Add support of nested paths #70

Closed grundic closed 8 years ago

grundic commented 8 years ago

Hello! Great library, lightweight and not overwhelmed -- thanks a lot!

Can you add possibility to specify field disposition in case it's not at root level? Here is small example:

from jsonmodels import models, fields

class User(models.Base):
    name = fields.StringField()
    salary = fields.IntField()

data = {
    'name': 'John Smith',
    'data': {
        'salary': '100500'
    },

}

if __name__ == '__main__':
    user = User(**data)
    print(user.name)
    print(user.salary)

I would like to be able to specify in User model that the salary is nested under data path. And it should be possible to specify nested path. List of strings or usual uri should work fine:

class User(models.Base):
    name = fields.StringField()
    salary = fields.IntField(nested=['some', 'path'])
    # or
    salary = fields.IntField(nested='/some/path')
grundic commented 8 years ago

Found a way to overcome it with additional class:


from jsonmodels import models, fields

class User(models.Base):
    class _Data(models.Base):
        salary = fields.IntField('data')

    name = fields.StringField()
    data = fields.EmbeddedField(_Data)

data = {
    'name': 'John Smith',
    'data': {
        'salary': 100500
    },
}

if __name__ == '__main__':
    user = User(**data)
    print(user.name)
    print(user.data.salary)

But this introduces complexity and maybe is not very transparent. I've made naive implementation of it. If you wish, I can create pull request for this.

beregond commented 8 years ago

@grundic

well, can't do this - since "Explicit is better than implicit."

This would add complexity. The worst part it would hidden complexity. It was designed to be rather readable, so you should use embedded field with additional class, even if this is a bit noisy.

grundic commented 8 years ago

Okay, thanks.