Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列表的Python json_Python_Json_List - Fatal编程技术网

列表的Python json

列表的Python json,python,json,list,Python,Json,List,我有一个我定义的对象列表 此时,我正在迭代列表中的每个元素,并将其转储到一个文件中。但当我想重新创建对象时,我遇到了问题: f = open(path, 'w') for element in ListOfElements: json.dump(element.__dict__, f) f.close() 尝试重新创建对象时,我会执行以下操作: a = json.JSONDecoder(object_hook = Element.from_json).decode(f.read())

我有一个我定义的对象列表

此时,我正在迭代列表中的每个元素,并将其转储到一个文件中。但当我想重新创建对象时,我遇到了问题:

f = open(path, 'w')
for element in ListOfElements:
    json.dump(element.__dict__, f)
f.close()
尝试重新创建对象时,我会执行以下操作:

a = json.JSONDecoder(object_hook = Element.from_json).decode(f.read())
但这非常糟糕,因为我必须在文件中的对象之间引入某种拆分器。那么它就不再是一个“真正的”json了。 有没有办法做点什么

json.dump(ListOfElements, f) #this exact code gives me "... is not JSON serializable"

然后创建一个能够重新创建整个列表的文件?

要存储对象,请使用python内置的pickle或cPickle模块。这些是专门为存储对象而创建的

请从中检查此示例

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
  pickle.dump(a, handle)

with open('filename.pickle', 'rb') as handle:
  b = pickle.load(handle)

print a == b