用Python将对象保存到JSON或XML文件中 [英] Save objects into JSON or XML file in Python

查看:507
本文介绍了用Python将对象保存到JSON或XML文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了要保存在JSON或XML文件中的对象(使用tkinter小部件),以便在启动后可以恢复它们.

I create objects (using tkinter widgets) that I wish to save in a JSON or XML file, so that I can recover them after startup.

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 现在.)

(I'm a bit lost with http://docs.python.org/2/library/json.html right now.)

推荐答案

文档中已提及,请使用

It's mentioned in the docs, use json.dump.

使用示例:

import json

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

在您的情况下,您不能将对象本身转换为json格式.仅保存信息:

In your case, you can't convert the object itself to a json format. Save the information only:

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'])

这篇关于用Python将对象保存到JSON或XML文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆