I'm looking through the json documentation and I'm trying to understand how to actually convert a Python object into JSON data, and then convert that data back into a Python object. I understand you can pass lists, dicts, and tuples of "primitives" like in the example at the top, but I tried creating a very minimal object and passing it to json.dumps() and got "object is not JSON serializable".
What is the proper way to make an object JSON serializable? I'm currently imagining writing a method which converts my object into a dictionary then passes it to json.dump() and a parallel method to take the dictionary and construct a new object from it. However that seems really redundant and limited, so I feel like there must be something I'm missing. Can anyone help fill me in?
Take a look at load() and dump(); each accept an object_hook function to decode and encode objects not ordinarily JSONable. Maybe this will do for you.
The following snipped of code illustrates several aspects of working with JSON in Python 3. Take note of the JSONEncoder class and the implementation of encoding decimal and datetime.
import json
from decimal import Decimal
from datetime import datetime, date
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Decimal):
return float(o)
elif isinstance(o, (datetime, date)):
return o.isoformat()
return super().default(self,o)
class JSONDecoder(json.JSONDecoder):
pass
_Default_Encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=False,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
default=None,
)
_Default_Decoder = JSONDecoder(
object_hook=None,
object_pairs_hook=None
)
Encode = _Default_Encoder.encode
Decode = _Default_Decoder.decode
来源:https://stackoverflow.com/questions/4882189/json-usage-in-python