edelooff / sqlalchemy-json

Full-featured JSON type with mutation tracking for SQLAlchemy
http://variable-scope.com/posts/mutation-tracking-in-nested-json-structures-using-sqlalchemy
BSD 2-Clause "Simplified" License
189 stars 34 forks source link

NestedMutableJson to dict #14

Closed irux closed 5 years ago

irux commented 6 years ago

Hi. I would like to cast the NestedMutableJson to dict.

What can be the best solution for this problem ?

thank you

edelooff commented 6 years ago

Not sure exactly at which point you want to do this. At the Python side, the data is, in most cases, already a dict.

If it's data going into the database that should be a dict, that sounds like a validation problem, which can either be tackled at the SQLAlchemy level using something like sqlalchemy.orm.validates, or a more comprehensive validation library like marshmallow.

If it's about data coming out of the database that ought to be a dict, you could create a subclass of the NestedMutableJson which overrides the process_result_value method to force whatever isn't a dict into a dict. That's going to be a rather application-specific pattern, because the key under which the value goes is rather arbitrary. Something like this might provide a start:

class ForceDictNestedJson(NestedMutableJson):
    def process_result_value(value, dialect):
        value = super(ForceDictNestedJson, self).process_result_value(value, dialect)
        if not isinstance(value, dict):
            return {'_dict_wrapper': value}
        return value
edelooff commented 5 years ago

If there's an issue here that ought to be resolved by sqlalchemy-json, please update.