Ticket #115 (new enhancement)

Opened 15 months ago

Last modified 15 months ago

Entity.to_dict aims to provide a JSON style structure, but date types are not converted to string

Reported by: guest Owned by:
Priority: normal Milestone:
Component: core Version: 0.7.1
Keywords: Cc:

Description

Hello there,

I'm writing a small application that exposes a JSON API. To make my life easier, I've decided to use the Entity.to_dict' method. But it does not convert datetime objects into string. This breaks, for example, simplejson.dumps' calls.

The problem is that JSON RFC 4627 does not say which format should be used. So, I'd like to suggest to convert dates to the iso8601[0] format that seems to cover almost everything about date representation. It's also good to say that dojo (that javascript library) already uses it as its date format.

In case you think it's a reasonable feature to add to elixir, I think that a simple `strftime' call does the job.

While we don't find a definitive solution I'll extend the Entity class in my app code overriding the to_dict method. but if you're interested, I can provide a patch that changes this directly in elixir.

[0] http://en.wikipedia.org/wiki/ISO_8601

Thanks a lot for this amazing software :)

-- Lincoln de Sousa <lincoln@…>

Change History

Changed 15 months ago by guest

Since it's not a final solution, this is the way I'm handling it:

class MyEntity(EntityBase):

    __metaclass__ = EntityMeta

    def to_dict(self, deep={}, exclude=[]):
        iso8601_datetime = "%Y-%m-%dT%H:%M:%S"
        iso8601_date = "%Y-%m-%d"
        data = super(MyEntity, self).to_dict(deep, exclude)

        for key, value in data.items():
            if isinstance(value, date):
                data[key] = value.strftime(iso8601_date)
            if isinstance(value, datetime):
                data[key] = value.strftime(iso8601_datetime)
        return data

Changed 15 months ago by ged

Well, I'm not thrilled by the idea of including this in the core. It is a choice that I'd rather leave to the user. Some people might want the dict-like structure with date as python objects and not strings. It does make a nice recipe though so if you could add it to our recipe page, that'd be great!

Note: See TracTickets for help on using tickets.