1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
from utilities import ensure_no_files_overwritten
import jsonpickle
ensure_no_files_overwritten(
expected_contents='{"py/object": "__main__.Example", "data": {"BAR": 1, "foo": 0}}'
)
class Example:
def __init__(self):
self.data = {"foo": 0, "BAR": 1}
def get_foo(self):
return self.data["foo"]
def __eq__(self, other):
# ensure that jsonpickle preserves important stuff like data across encode/decoding
return self.data == other.data and self.get_foo() == other.get_foo()
# instantiate the class
ex = Example()
# encode the class. this returns a string, like json.dumps
encoded_instance = jsonpickle.encode(ex)
assert (
encoded_instance
== '{"py/object": "__main__.Example", "data": {"BAR": 1, "foo": 0}}'
)
print(
f"jsonpickle successfully encoded the instance of the Example class! It looks like: {encoded_instance}"
)
with open("example.json", "w+") as f:
f.write(encoded_instance)
print(
"jsonpickle successfully wrote the instance of the Example class to example.json!"
)
with open("example.json", "r+") as f:
written_instance = f.read()
# decode the file into a copy of the original object
decoded_instance = jsonpickle.decode(written_instance)
print("jsonpickle successfully decoded the instance of the Example class!")
# this should be true, if it isn't then you should file a bug report
assert decoded_instance == ex
print(
"jsonpickle successfully decoded the instance of the Example class, and it matches the original instance!"
)
|