How To Save A Dictionary Of Objects?
Solution 1:
What you might be able to do is saving the instance's attributes to a CSV-file and then just create it when starting up. This might be a bit too much code and is possible not the best way. One obvious problem is that it doesn't work if you don't have the same amount of attributes as parameters, which should be possible to fix if necessary I believe. I just thought I might try and post and see if it helps :)
import json
classTrampoline:
def__init__(self, color, size, height, spring):
self.color = color
self.size = size
self.height = height
self.spring = spring
def__repr__(self):
return"Attributes: {}, {}, {}, {}".format(self.color, self.size, self.height, self.spring)
my_dict = {
"name1": Trampoline('red', 100, 2.3, True),
"name2": Trampoline('blue', 50, 2.1, False),
"name3": Trampoline('green', 25, 1.8, True),
"name5": Trampoline('white', 10, 2.6, False),
"name6": Trampoline('black', 0, 1.4, True),
"name7": Trampoline('purple', -33, 3.0, True),
"name8": Trampoline('orange', -999, 2.5, False),
}
defsave(my_dict):
withopen('save_file.txt', 'w') as file:
temp = {}
for name, instance in my_dict.items():
attributes = {}
for attribute_name, attribute_value in instance.__dict__.items():
attributes[attribute_name] = attribute_value
temp[name] = attributes
json.dump(temp, file)
defload():
withopen('save_file.txt', 'r') as file:
my_dict = {}
x = json.load(file)
for name, attributes in x.items():
my_dict[name] = Trampoline(**attributes)
return my_dict
# CHECK IF IT WORKS!
save(my_dict)
my_dict = load()
print("\n".join(["{} | {}".format(name, instance) for name, instance insorted(my_dict.items())]))
Solution 2:
Here is an example of a class that handles datetime objects.
classCustomEncoder(json.JSONEncoder):
defdefault(self, obj):
ifisinstance(obj, datetime.datetime):
if obj.tzinfo:
obj = obj.astimezone(isodate.tzinfo.UTC).replace(tzinfo=None)
return obj.isoformat()[:23] + 'Z'return json.JSONEncoder.default(self, obj)
when you encode to json the default
function of the cls
is called with object you passed. If you want to handle a type that is not part of the standard json.JSONEncoder.default
you need to intercept it and return how you want it handled as a valid json type. In this example I turned the datetime
into a str
and returned that. If its not one of the types I want to special case, I just pass it along to the standard json.JSONEncoder.default
handler.
To use this class you need to pass it in the cls
param of json.dump
or json.dumps
:
json.dumps(obj, cls=CustomEncoder)
Decoding is done the same way but with json.JSONDecoder
, json.load
, and json.loads
. However you can not match on type, so you will need to either add an 'hint' in encoding for decoding or know what type it needs to decode.
Solution 3:
For a simple class, you can make an easy serializer as below. This will take all of the properties of your Trampoline
object and put them into a dictionary and then into JSON.
classTrampoline(object):
...
defserialize(self):
return json.dumps(vars(self))
If your class is a bit more complicated, then write a more complicated serializer :)
Post a Comment for "How To Save A Dictionary Of Objects?"