用Python将对象保存到JSON或XML文件中

2024-10-05 14:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建要保存在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有点迷茫。)


Tags: 文件the对象selftxtjsonhere部件
3条回答

请参阅更新:jsonsimplejson

如果您有一个简单的对象,json.dump(用于文件导出)和json.dumps(用于字符串导出)非常有用。 但是,如果需要保存更复杂的数据结构(如字典) 充满了字典{'a':{...}, 'b':2}json从标准库斗争。

对于这种情况,像simplejson这样的工具可能很有用。 http://simplejson.readthedocs.org/en/latest/

>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps(u'\u1234'))
"\u1234"

因为您需要将复杂的列表L保存为json,所以我将使用simplejson。类似于:

import simplejson as json
with open('Texte.json', 'w') as texte_file:
    json.dump(L, texte_file)`

更新:simplejson来自标准库(在2.6中添加到标准库)。有关详细信息,请参见:What are the differences between json and simplejson Python modules?

文档中提到过,使用^{}

使用示例:

import json

data = {'a':1, 'b':2}
with open('my_json.txt', 'w') as fp:
    json.dump(data, fp)

在您的例子中,不能将对象本身转换为json格式。仅保存信息:

data = {'a':(10, 20, 'blah'), 'b':(20, 70, 'blah2')
with open('my_json.txt', 'w') as fp:
     json.dump(data, fp)

当你把它装回去时:

with open('my_json.txt') as fp:
    data = json.loads(fp)
    a = Texte(*data['a'])
    b = Texte(*data['b'])

如果从未在应用程序之外修改这些对象,为什么需要JSON或XML? 如果不在应用程序外部更改数据,则可以使用pickle模块将对象序列化并反序列化为二进制数据或ASCII字符串,然后保存这些数据。

有关详细信息,请参见: http://docs.python.org/2/library/pickle.html

还有一个第三方库,它支持将类存储为JSON。 http://jsonpickle.github.io/

虽然我自己还没有使用过它,所以不确定输出的可读性如何,但是如果您只想将其存储为文件并在应用程序重新启动后重新加载,那么我看不出JSON/XML比使用Pickle有什么优势。

编辑:正如其他人指出的,您可以使用cPickle而不是pickle来获得更好的性能。算法是相同的,所以使用它们的方式完全相同。

相关问题 更多 >