【问题标题】:How to read/make sense of a PHP serialised data string in python如何在 python 中读取/理解 PHP 序列化数据字符串
【发布时间】:2023-03-10 13:04:01
【问题描述】:

我通过 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 写入数据库的。

【问题讨论】:

  • 这是通过什么序列化的?

标签: python django serialization


【解决方案1】:

phpserialize:

将php的serializeunserialize函数移植到python。本模块实现python序列化接口(如:提供dumpsloads等功能)...

【讨论】:

  • 这正是我所需要的。谢谢你,干杯!
【解决方案2】:

这是一个非常粗略且不完整的实现:

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, typ

【讨论】:

    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多