Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save objects into JSON or XML file in Python

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()

How can save and restore these objects with JSON or XML ?

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

like image 671
Basj Avatar asked Dec 25 '22 16:12

Basj


1 Answers

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

Example of use:

import json

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

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)

And when you load it back:

with open('my_json.txt') as fp:
    data = json.loads(fp)
    a = Texte(*data['a'])
    b = Texte(*data['b'])
like image 89
aIKid Avatar answered Jan 06 '23 20:01

aIKid