我创建要保存在JSON或XML文件中的对象(使用tkinter
小部件),以便在启动后恢复它们。
from Tkinter import *
class Texte:
def __init__(self, ax, ay, txt):
self.entry = Entry(root,bd=0,font=("Purisa",int(15)))
self.entry.insert(0, txt)
self.x = ax
self.y = ay
self.entry.place(x=self.x,y=self.y)
root = Tk()
a = Texte(10, 20, 'blah')
b = Texte(20, 70, 'blah2')
# here the user will modify the entries' x, y, txt, etc.
L = [a,b]
# here save the list L (containing the Texte objects) into a JSON file or XML so that I can recover them after restart
root.mainloop()
如何使用JSON或XML保存和还原这些对象?
(我现在对http://docs.python.org/2/library/json.html有点迷茫。)
请参阅更新:
json
是simplejson
。如果您有一个简单的对象,
json.dump
(用于文件导出)和json.dumps
(用于字符串导出)非常有用。 但是,如果需要保存更复杂的数据结构(如字典) 充满了字典{'a':{...}, 'b':2}
json
从标准库斗争。对于这种情况,像
simplejson
这样的工具可能很有用。 http://simplejson.readthedocs.org/en/latest/因为您需要将复杂的列表
L
保存为json,所以我将使用simplejson
。类似于:更新:
simplejson
来自标准库(在2.6中添加到标准库)。有关详细信息,请参见:What are the differences between json and simplejson Python modules?。文档中提到过,使用^{} 。
使用示例:
在您的例子中,不能将对象本身转换为json格式。仅保存信息:
当你把它装回去时:
如果从未在应用程序之外修改这些对象,为什么需要JSON或XML? 如果不在应用程序外部更改数据,则可以使用pickle模块将对象序列化并反序列化为二进制数据或ASCII字符串,然后保存这些数据。
有关详细信息,请参见: http://docs.python.org/2/library/pickle.html
还有一个第三方库,它支持将类存储为JSON。 http://jsonpickle.github.io/
虽然我自己还没有使用过它,所以不确定输出的可读性如何,但是如果您只想将其存储为文件并在应用程序重新启动后重新加载,那么我看不出JSON/XML比使用Pickle有什么优势。
编辑:正如其他人指出的,您可以使用cPickle而不是pickle来获得更好的性能。算法是相同的,所以使用它们的方式完全相同。
相关问题 更多 >
编程相关推荐