PHP的cPickle反序列化来自PHP?

Cia*_*tic 6 php python serialization json pickle

我必须在PHP中序列化使用Python中的cPickle序列化的字典.

在这个特定情况下,我可能只是想要获取所需信息,但是有更好的方法吗?PHP的任何扩展都允许我在整个字典中更加原生地反序列化?

显然它在Python中被序列化,如下所示:

import cPickle as pickle

data = { 'user_id' : 5 }
pickled = pickle.dumps(data)
print pickled
Run Code Online (Sandbox Code Playgroud)

这种序列化的内容不能轻易粘贴到此处,因为它包含二进制数据.


由于Python结尾是Django,我最终创建了自己的JSONSessionStore.

mip*_*adi 7

如果要在使用不同语言编写的程序之间共享数据对象,则可能更容易使用JSON等序列化/反序列化.大多数主要的编程语言都有一个JSON库.

  • Python 2.6+内置了它,而早期版本则有simplejson. (2认同)
  • 虽然这是个好主意,但序列化部分并不在我的控制之下. (2认同)

Eri*_*arr 5

你可以打电话吗?您可以使用这样的python脚本将pickle数据转换为json:

# pickle2json.py
import sys, optparse, cPickle, os
try:
    import json
except:
    import simplejson as json

# Setup the arguments this script can accept from the command line
parser = optparse.OptionParser()
parser.add_option('-p','--pickled_data_path',dest="pickled_data_path",type="string",help="Path to the file containing pickled data.")
parser.add_option('-j','--json_data_path',dest="json_data_path",type="string",help="Path to where the json data should be saved.")
opts,args=parser.parse_args()

# Load in the pickled data from either a file or the standard input stream
if opts.pickled_data_path:
    unpickled_data = cPickle.loads(open(opts.pickled_data_path).read())
else:
    unpickled_data = cPickle.loads(sys.stdin.read())

# Output the json version of the data either to another file or to the standard output
if opts.json_data_path:
    open(opts.json_data_path, 'w').write(json.dumps(unpickled_data))
else:
    print json.dumps(unpickled_data)
Run Code Online (Sandbox Code Playgroud)

这样,如果从文件中获取数据,您可以执行以下操作:

<?php
    exec("python pickle2json.py -p pickled_data.txt", $json_data = array());
?>
Run Code Online (Sandbox Code Playgroud)

或者如果你想将它保存到文件中:

<?php
    system("python pickle2json.py -p pickled_data.txt -j p_to_j.json");
?>
Run Code Online (Sandbox Code Playgroud)

上面的所有代码可能并不完美(我不是PHP开发人员),但是这样的东西对你有用吗?