2

I'm getting this error:

TypeError: datetime.datetime(2012, 2, 12, 0, 47, 6, 542000) is not JSON serializable

when jinja is trying to parse this line:

var root_node_info = eval({{ nd|tojson|safe }});

nd contains a bson object from my mongo database. One of the fields is a datetime object. How can I get flask to serialize this properly?

This is my mongokit model(in case its relevant)

class Item(Document):
    structure = {
        "tldr": unicode,
        "body": unicode,
        "user": unicode,
        "time_submitted": datetime.datetime,
        "upvotes": int,
        "downvotes": int,
        "tags": [unicode]
    }

    validators = {
    }

    indexes = [
        {'fields':['user']},
        {'fields':['tags']}
    ]

    use_dot_notation = True

    required_fields = ['body', 'user', 'time_submitted']
    default_values = {'time_submitted': datetime.datetime.utcnow}

    def __repr__(self):
        return '<item %r>' % (self._id)
y3di
  • 673
  • 2
  • 8
  • 13

2 Answers2

5

JSON does not handle datetime objects. Standard practice is to encode them as strings in ISO format. This SO question about JSON provides examples. You will need to register the new JSON encoder filter yourself.

Community
  • 1
  • 1
Alex Morega
  • 4,132
  • 1
  • 24
  • 25
2

Just to be noted.

As of v0.10 Flask has the ability to specify your own json_encoder.

And Flask’s default JSONEncoder is aware of dates (and few other additional things).

Community
  • 1
  • 1
nilfalse
  • 2,380
  • 2
  • 19
  • 16