How to serialize SqlAlchemy result to JSON?

后端 未结 27 1865
说谎
说谎 2020-11-22 09:59

Django has some good automatic serialization of ORM models returned from DB to JSON format.

How to serialize SQLAlchemy query result to JSON format?

I tried

27条回答
  •  醉梦人生
    2020-11-22 10:28

    Here is a solution that lets you select the relations you want to include in your output as deep as you would like to go. NOTE: This is a complete re-write taking a dict/str as an arg rather than a list. fixes some stuff..

    def deep_dict(self, relations={}):
        """Output a dict of an SA object recursing as deep as you want.
    
        Takes one argument, relations which is a dictionary of relations we'd
        like to pull out. The relations dict items can be a single relation
        name or deeper relation names connected by sub dicts
    
        Example:
            Say we have a Person object with a family relationship
                person.deep_dict(relations={'family':None})
            Say the family object has homes as a relation then we can do
                person.deep_dict(relations={'family':{'homes':None}})
                OR
                person.deep_dict(relations={'family':'homes'})
            Say homes has a relation like rooms you can do
                person.deep_dict(relations={'family':{'homes':'rooms'}})
                and so on...
        """
        mydict =  dict((c, str(a)) for c, a in
                        self.__dict__.items() if c != '_sa_instance_state')
        if not relations:
            # just return ourselves
            return mydict
    
        # otherwise we need to go deeper
        if not isinstance(relations, dict) and not isinstance(relations, str):
            raise Exception("relations should be a dict, it is of type {}".format(type(relations)))
    
        # got here so check and handle if we were passed a dict
        if isinstance(relations, dict):
            # we were passed deeper info
            for left, right in relations.items():
                myrel = getattr(self, left)
                if isinstance(myrel, list):
                    mydict[left] = [rel.deep_dict(relations=right) for rel in myrel]
                else:
                    mydict[left] = myrel.deep_dict(relations=right)
        # if we get here check and handle if we were passed a string
        elif isinstance(relations, str):
            # passed a single item
            myrel = getattr(self, relations)
            left = relations
            if isinstance(myrel, list):
                mydict[left] = [rel.deep_dict(relations=None)
                                     for rel in myrel]
            else:
                mydict[left] = myrel.deep_dict(relations=None)
    
        return mydict
    

    so for an example using person/family/homes/rooms... turning it into json all you need is

    json.dumps(person.deep_dict(relations={'family':{'homes':'rooms'}}))
    

提交回复
热议问题