Python 的 cPickle 从 PHP 反序列化?
我必须在 PHP 中反序列化字典,而该字典是在 Python 中使用 cPickle 序列化的。
在这种特定情况下,我可能可以regexp想要的信息,但是有更好的方法吗? PHP 是否有任何扩展可以让我以更原生的方式反序列化整个字典?
显然它在Python中是这样序列化的:
import cPickle as pickle
data = { 'user_id' : 5 }
pickled = pickle.dumps(data)
print pickled
这种序列化的内容不能轻易粘贴到这里,因为它包含二进制数据。
I have to deserialize a dictionary in PHP that was serialized using cPickle in Python.
In this specific case I probably could just regexp the wanted information, but is there a better way? Any extensions for PHP that would allow me to deserialize more natively the whole dictionary?
Apparently it is serialized in Python like this:
import cPickle as pickle
data = { 'user_id' : 5 }
pickled = pickle.dumps(data)
print pickled
Contents of such serialization cannot be pasted easily to here, because it contains binary data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想在用不同语言编写的程序之间共享数据对象,则使用 JSON< 之类的内容进行序列化/反序列化可能会更容易/a> 相反。大多数主要编程语言都有 JSON 库。
If you want to share data objects between programs written in different languages, it might be easier to serialize/deserialize using something like JSON instead. Most major programming languages have a JSON library.
可以进行系统调用吗?您可以使用这样的 python 脚本将 pickle 数据转换为 json:
这样,如果您从文件中获取数据,您可以执行如下操作:
或者如果您想将其保存到文件中,则:
所有代码上面的内容可能并不完美(我不是 PHP 开发人员),但是这样的东西对你有用吗?
Can you do a system call? You could use a python script like this to convert the pickle data into json:
This way, if your getting the data from a file you could do something like this:
or if you want to save it out to a file this:
All the code above probably isn't perfect (I'm not a PHP developer), but would something like this work for you?
我知道这很古老,但我只需要为 Django 1.3 应用程序(大约 2012 年)执行此操作并发现:
https://github.com/terryf/Phpickle
因此,以防万一,有一天,其他人需要相同的解决方案。
I know this is ancient, but I've just needed to do this for a Django 1.3 app (circa 2012) and found this:
https://github.com/terryf/Phpickle
So just in case, one day, someone else needs the same solution.
如果 pickle 是由您显示的代码创建的,那么它不会包含二进制数据 - 除非您将换行符称为“二进制数据”。请参阅Python 文档。以下代码由 Python 2.6 运行。
以上哪一个看起来最像您所看到的?您可以发布由十六进制编辑器/转储器或任何与 Python 的 repr() 等价的 PHP 显示的腌制文件内容吗?典型的字典中有多少个项目?除了“整数”和“8 位字节字符串”之外还有哪些数据类型(什么编码?)?
If the pickle is being created by the the code that you showed, then it won't contain binary data -- unless you are calling newlines "binary data". See the Python docs. Following code was run by Python 2.6.
Which of the above looks most like what you are seeing? Can you post the pickled file contents as displayed by a hex editor/dumper or whatever is the PHP equivalent of Python's repr()? How many items in a typical dictionary? What data types other than "integer" and "string of 8-bit bytes" (what encoding?)?