2016-09-30 05:03:09 +02:00
|
|
|
"""
|
|
|
|
This module implements a custom JSON writer to be able to serialize data
|
|
|
|
returned by Weboob and pretty print the output JSON.
|
2016-09-30 17:37:29 +02:00
|
|
|
|
|
|
|
Based upon
|
|
|
|
http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python.
|
2016-09-30 05:03:09 +02:00
|
|
|
"""
|
2016-09-28 21:38:55 +02:00
|
|
|
import json
|
|
|
|
|
2016-09-29 05:09:14 +02:00
|
|
|
from datetime import date, datetime
|
2016-09-28 21:38:55 +02:00
|
|
|
from decimal import Decimal
|
|
|
|
|
|
|
|
|
|
|
|
class CustomJSONEncoder(json.JSONEncoder):
|
|
|
|
"""
|
|
|
|
Custom JSONEncoder to support more types.
|
|
|
|
"""
|
|
|
|
def default(self, o):
|
2016-09-29 05:09:14 +02:00
|
|
|
if isinstance(o, datetime) or isinstance(o, date):
|
2016-09-28 21:38:55 +02:00
|
|
|
# Serialize datetime objects to ISO dates
|
|
|
|
return o.isoformat()
|
|
|
|
elif isinstance(o, Decimal):
|
|
|
|
# Serialize Decimal objects to string
|
|
|
|
return str(o)
|
|
|
|
return json.JSONEncoder.default(self, o)
|
|
|
|
|
|
|
|
|
2016-09-30 05:03:09 +02:00
|
|
|
def pretty_json(obj):
|
2016-09-28 21:38:55 +02:00
|
|
|
"""
|
|
|
|
Pretty printing of JSON output, using the custom JSONEncoder.
|
2016-09-30 05:03:09 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
obj: the object to JSON serialize.
|
|
|
|
Returns:
|
|
|
|
the pretty printed JSON string.
|
2016-09-28 21:38:55 +02:00
|
|
|
"""
|
2016-09-30 05:03:09 +02:00
|
|
|
return json.dumps(obj, sort_keys=True,
|
2016-09-28 21:38:55 +02:00
|
|
|
indent=4, separators=(',', ': '),
|
|
|
|
cls=CustomJSONEncoder)
|