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