1

This is a little bit complicated but I try to explain as best as I can. I have a class called Event with two attributes:

self.timestamp= datetime.now()
self.data = this is a big dictionary

I put all the instances of this class into a list and finally use json.dumps() to print the whole list to a file. json.dumps(self.timeline, indent=4, default=json_handler) I am using a python environment where I can install/modify libraries and I only have access to python json <= 2.7.

This is my workaround to handle datetime:

# workaround for python json <= 2.7 datetime serializer
def json_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, event.Event):
        return {obj.__class__.__name__ : obj.data}
    else:
        raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))

and everything seemed to work fine until I noticed that json does not print any timestamp. Why is that? what is happening?

1 Answer 1

1

When the serializer encounters your event.Event type you're only serializing its data attribute skipping the timestamp completely. You need to return the timestamp as well somehow. Maybe something like:

def json_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, Event):
        attrs = dict(data=obj.data, timestamp=obj.timestamp)
        return {obj.__class__.__name__: attrs}
    else:
        raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I knew that I had to return the time-stamps as well but I did not know how to do it only. I will test this and let you know as well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.