我通过Django访问的一个遗留数据库有一个表列,它以以下字符串格式存储序列化的数据:
a:5:{i:1;s:4:"1869";i:2;s:4:"1859";i:3;s:4:"1715";i:4;s:1:"0";i:5;s:1:"0";}有没有什么方法可以使用python/ python -library将其转换为列表或任何其他友好的python数据类型,以便进一步处理单个值?
注意:这些值是通过PHP写入数据库的。
发布于 2011-03-24 00:41:41
phpserialize
将php的serialize和unserialize函数的一个端口
到python。此模块实现python序列化接口(例如:提供转储、加载和类似功能)...
发布于 2015-07-02 20:20:59
下面是一个非常粗糙和不完整的实现:
def p(f, d): # parse until
data = []
b = f.read(1)
while b and b != d:
data.append(b)
b = f.read(1)
return b''.join(data)
def parse(f):
if not hasattr(f, 'read'):
import io
try:
f = io.BytesIO(f)
except TypeError:
f = io.BytesIO(f.encode('utf-8'))
typ = f.read(2)
if typ == b'i:':
return int(p(f, b';'))
if typ == b'd:':
return float(p(f, b';'))
if typ == b's:':
return f.read(int(p(f, b':')) + 3)[1:-2].decode('utf-8')
if typ == b'a:':
l = int(p(f, b':'))
f.read(1) # {
items = [(parse(f), parse(f)) for i in range(l)]
f.read(1) # }
return dict(items)
assert False, typhttps://stackoverflow.com/questions/5408599
复制相似问题