3

I am trying to use Flask-Ask and create an Alexa skill. I am getting issue while storing date and time into json

Below is the error

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2018, 6, 12) is not JSON serializable

Below is the code snippet

@ask.intent("BookDateConfirmIntent")
def booking_confirmed(confirm_date):

    start_date = session['attributes']['startDate']
    data = {'services': '1234a', 'startDate': start_date, 'message': 'booking confirmed'}
    print json.dumps(data, indent=4, sort_keys=True, default=str)

The date being passed is like 2018-06-12

I read that we need to serialize this and I am not able to get it working correctly for the above code requirement. Someone please help. Thanks

RaghuCK
  • 105
  • 3
  • 12
  • You need to make sure `start_date` is a string, not a `datetime` object. – rst-2cv Jun 11 '18 at 07:56
  • Is this helpful : https://code-maven.com/serialize-datetime-object-as-json-in-python – Nikhil Wagh Jun 11 '18 at 07:58
  • @NikhilWagh Thanks I read this, but I am not taking the present datetime. I am passing date and time which is unique like for doing appointment. Can you please change the above code accordingly which will be helpful. – RaghuCK Jun 11 '18 at 08:07

2 Answers2

2

You can try type-casting the datetime object to string.

Change start_date to str(start_date).

akshat
  • 1,219
  • 1
  • 8
  • 24
1

It doesn't matter whether you're taking present datetime or some in particular. What matters is the type(start_date) is datetime.date.

You can try something like this:

def myconverter(o):
    if isinstance(o, datetime.date):
        return "{}-{}-{}".format(o.year, o.month, o.day)

def booking_confirmed(confirm_date):

    start_date = myconverter(session['attributes']['startDate'])
    data = {'services': '1234a', 'startDate': start_date, 'message': 'booking confirmed'}
    print json.dumps(data, indent=4, sort_keys=True, default=str)
Nikhil Wagh
  • 1,376
  • 1
  • 24
  • 44
  • what is `type(session['attributes']['startDate'])`? – Nikhil Wagh Jun 11 '18 at 09:18
  • I have imported it from the flask_ask framework `from flask_ask import Ask, statement, question, session` – RaghuCK Jun 11 '18 at 11:31
  • what does this print for you? `print type(session['attributes']['startDate'])` – Nikhil Wagh Jun 11 '18 at 11:34
  • '' I fixed this problem by converting to string.. but this `session.attributes = save_booking_date(BookingDate)` overwrites the existing attribute. Can you please tell me how to append the attributes in session ? – RaghuCK Jun 11 '18 at 12:14
  • I'm unable to understand what you're trying to do. What does `save_booking_date(BookingDate)` returns. And if you don't want to it to overwrite create a new `key` (It's a dictionary). Or else just append it `+=`. – Nikhil Wagh Jun 11 '18 at 12:31