'Pythonic JSON encode/decode of object containing dictionary instance variables
Let's say I have a python class that has instance variables that are dictionaries. I'm new-ish to JSON and looking for the most pythonic way to encode/decode lists of these objects to/from .json files.
I'm curious if there is a clever way to use an object_hook to decode things that contain dictionaries as the typical encoder works inside->out as I understand. I guess I could encode the dictionary into an ugly list of 2-item lists (??) and then handle that with the decoder?
Here's what I've got now in a reproducible example. It works, but I suspect that it could be improved. Curious if there is a way to handle this with custom decoder or object_hook or other pythonic approach
import json
from typing import Dict
class Critic():
def __init__(self, name: str, reviews: Dict[str, int]):
self.name = name
self.reviews = reviews
@staticmethod
def encode(obj):
return {"name": obj.name, "reviews": obj.reviews}
@staticmethod
def decode(obj):
# ??? Can it be done ???
pass
def __repr__(self):
return f'{self.name}, {self.reviews}'
x1 = Critic('Bob', {'Jaws':4, 'Star Wars':5})
x2 = Critic('Jim', {'Dune':3, 'Top Gun 2':4})
data = json.dumps([x1, x2], default=Critic.encode, indent=2)
#print(data)
# load it, then parse the result "manually"
retrieved = json.loads(data)
res = []
for item in retrieved:
res.append(Critic(**item))
print(res)
Yields (as expected):
[Bob, {'Jaws': 4, 'Star Wars': 5}, Jim, {'Dune': 3, 'Top Gun 2': 4}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
