title: Convert SqlAlchemy orm result to dict
body: <p>How to convert SQLAlchemy orm object result to JSON format?</p>
  
  <p>Currently I am using sqlalchemy reflection to reflect tables from the DB.
  Consider I have a User table and a Address table I am reflecting fro the DB.
  The user entity has one to one relationship with the address entity.
  Below is the code to reflect the table from the DB and use the mapper class to map the relationship.</p>
  
  <pre><code>from sqlalchemy import Table
  from sqlalchemy.orm import mapper, relationship
  user_reflection = Table('user', metadata, autoload=True, autoload_with=engine)
  class User(object):
      def __init__(self, id, name, dob):
          self.id = id
          self.name = name
          self.dob = dob
  address_reflection = Table('address', metadata, autoload=True, autoload_with=engine)
  mapper(User,
         user_reflection,
         properties={
             'address': relationship(SourceAddress, uselist=False)
         }
  )
  </code></pre>
  
  <p>Now when I query the object using sqlalchemy orm</p>
  
  <pre><code>user = session.query(User).first()
  user_dict = object_to_dict(user)
  </code></pre>
  
  <p>Now, when I want to convert the user object to dict 
  I use the below method </p>
  
  <pre><code>def object_to_dict(obj):
      columns = [column.key for column in class_mapper(obj.__class__).columns]
      get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (c, getattr(obj, c))
      return dict(map(get_key_value, columns))
  </code></pre>
  
  <p>However, the object_to_dict methods works fine and returns a valid dic object if the returned user object that did not have a relationship with another table.
  If the user object has a relationship the object_to_dict method doesn't auto-expand relations object and convert it to dict.</p>
  
  <p>Could anyone suggest me how I could automatically determine if the returned user object has a relationship and expand the relationship object to a dict if it has one and so on for any number of child objects.</p>