2013-10-03 113 views
0

所以,我序列化,因爲這簡單的東西:如何在python中對列表進行序列化?

[{'username': u'username', '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x1d0e150>, 'updated_time_stamp': datetime.datetime(2013, 9, 23, 13, 38, 30, 775805), 'time_stamp': datetime.datetime(2013, 9, 23, 13, 38, 30, 775787), 'password': u'password', 'type': 'guru', 'id': 1}, {'username': u'satyajit', '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x1d0e610>, 'updated_time_stamp': datetime.datetime(2013, 9, 24, 8, 43, 55, 940195), 'time_stamp': datetime.datetime(2013, 9, 24, 8, 43, 55, 940188), 'password': u'$2a$12$Y7zcWXM1et3At.fdzzMZNV8eHpEjnYIdKbZl/wNNtaGW6G3cYVkp6OS', 'type': 'guru', 'id': 2}] 

這是一個列表,但具有時間標記,並json.dumps一個_sa_instance_state屬性拒絕連載彈出一個錯誤。

因此,我認爲寫我自己的序列且通過SO解決方案來爲它:

class PythonObjectEncoder(JSONEncoder): 
    def default(self, obj): 
     if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))): 
      return JSONEncoder.default(self, obj) 
     return {'_python_object': pickle.dumps(obj)} 

def as_python_object(dct): 
    if '_python_object' in dct: 
     return pickle.loads(str(dct['_python_object'])) 
    return dct 

當我運行它,現在我得到這樣的:

"[[{\"_python_object\": \"ccopy_reg\\n_reconstructor\\np0\\n(copentrade.libs.user.models\\nUserModel\\np1\\nc__builtin__\\nobject\\np2\\nNtp3\\nRp4\\n(dp5\\nS'username'\\np6\\nVusername\\np7\\nsS'_sa_instance_state'\\np8\\ng0\\n(csqlalchemy.orm.state\\nInstanceState\\np9\\ng2\\nNtp10\\nRp11\\n(dp12\\nS'class_'\\np13\\ng1\\nsS'modified'\\np14\\nI00\\nsS'committed_state'\\np15\\n(dp16\\nsS'instance'\\np17\\ng4\\nsS'callables'\\np18\\n(dp19\\nsS'key'\\np20\\n(g1\\n(I1\\ntp21\\ntp22\\nsS'expired'\\np23\\nI00\\nsbsS'updated_time_stamp'\\np24\\ncdatetime\\ndatetime\\np25\\n(S'\\\\x07\\\\xdd\\\\t\\\\x17\\\\r&\\\\x1e\\\\x0b\\\\xd6}'\\np26\\ntp27\\nRp28\\nsS'time_stamp'\\np29\\ng25\\n(S'\\\\x07\\\\xdd\\\\t\\\\x17\\\\r&\\\\x1e\\\\x0b\\\\xd6k'\\np30\\ntp31\\nRp32\\nsS'password'\\np33\\nVpassword\\np34\\nsS'type'\\np35\\nS'guru'\\np36\\nsS'id'\\np37\\nI1\\nsb.\"}, {\"_python_object\": \"ccopy_reg\\n_reconstructor\\np0\\n(copentrade.libs.user.models\\nUserModel\\np1\\nc__builtin__\\nobject\\np2\\nNtp3\\nRp4\\n(dp5\\nS'username'\\np6\\nVsatyajit\\np7\\nsS'_sa_instance_state'\\np8\\ng0\\n(csqlalchemy.orm.state\\nInstanceState\\np9\\ng2\\nNtp10\\nRp11\\n(dp12\\nS'class_'\\np13\\ng1\\nsS'modified'\\np14\\nI00\\nsS'committed_state'\\np15\\n(dp16\\nsS'instance'\\np17\\ng4\\nsS'callables'\\np18\\n(dp19\\nsS'key'\\np20\\n(g1\\n(I2\\ntp21\\ntp22\\nsS'expired'\\np23\\nI00\\nsbsS'updated_time_stamp'\\np24\\ncdatetime\\ndatetime\\np25\\n(S'\\\\x07\\\\xdd\\\\t\\\\x18\\\\x08+7\\\\x0eX\\\\xa3'\\np26\\ntp27\\nRp28\\nsS'time_stamp'\\np29\\ng25\\n(S'\\\\x07\\\\xdd\\\\t\\\\x18\\\\x08+7\\\\x0eX\\\\x9c'\\np30\\ntp31\\nRp32\\nsS'password'\\np33\\nV$2a$12$Y7zcWXM1et3At.fdMZNV8eHpEjnYIdKbZl/wNNtaGW6G3cYVkp6OS\\np34\\nsS'type'\\np35\\nS'guru'\\np36\\nsS'id'\\np37\\nI2\\nsb.\"}]]" 

我是有點困惑,爲什麼會發生這種情況,以及如何擺脫這個錯誤並正確地序列化它。任何幫助?

編輯:

這是我所得到的,當我試圖返回從的usermodel用戶列表使用SQLAlchemy的聲明。

File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 202, in default 
    raise TypeError(repr(o) + " is not JSON serializable") 

這發生在序列化我在頂部提到的完全相同的數據,其類型是一個列表。

@cherrypy.tools.json_out() 
def GET(self, account=None, request_type=None): 
    #return the order list for this account type 
    user = User() 
    usermodel = user.get_all() 
    #j = dumps(usermodel, cls=PythonObjectEncoder) 
    return usermodel 

這是我如何返回數據。目前我已註釋掉PythonObjectEncoder,因爲它不會幫助我的事業。

+0

爲什麼要序列化InstanceState?另外,你在說什麼錯誤?這些信息只是醃製數據,這將允許您反序列化它。 –

+0

我得到這個錯誤:文件「/usr/lib/python2.7/dist-packages/simplejson/encoder.py」,第202行,默認 引發TypeError(repr(o)+「不是JSON可序列化」) – Hick

+0

可能希望將其添加到您的問題中 - 如果您可以想出一個小例子,那也是非常棒的。 –

回答

0

您可能實際上並不想序列化整個模型。

一種方法是做一些像這樣:

class MyModel(Base): 
    __tablename__ = 'whatever' 

    name = Column(String, primary_key=True) 
    email = Column(String) 
    bio = Column(String) 

    # other code 

    def dict(self): 
     return {'name': self.name, 
       'email': self.email, 
       'bio': self.bio, 
       } 

然後,你做這樣的事情:

return [user.dict() for user in usermodel] 

此處可你最好的解決方案。

+0

那麼,如何返回列表的用戶? – Hick

+0

您確實需要用戶列表或代表他們的數據嗎? –