-2

I'm learning Python and aws.

What I want is to extract value from the JSON response. This code works for JSON response that doesn't contain date values, but in this case response contains date value.

Here is my code:

import datetime
from datetime import date, datetime
import boto3
import json

client = boto3.client('lex-models')

response = client.get_utterances_view(
          botName='CreateServicesBot',
          botVersions=[
                     '$LATEST',
                      ],
          statusType='Missed'
          )

with open('/tmp/output.json', 'w') as data:
          json.dump(response,data)

with open('/tmp/output.json') as f:
          data = json.load(f)
ustr=data["utteranceString"]
print ustr

I'm getting this error:

TypeError: datetime.datetime(2018, 6, 7, 9, 44, 38, 146000, tzinfo=tzlocal()) is not JSON serializable

Does someone know the solution? thx

Beastn
  • 1
  • 1
  • 1
  • 2

2 Answers2

6

As the error suggests you are trying to dump into json a datetime.datetime object and this is not possible.

What you can do, is to convert those objects into a string and then dump it. Say that the field which contains a datetime.datetime is called date then you need to do the following before exporting to the json file

response[date] = response[date].strftime("%Y-%m-%d %H:%M:%S")
kosnik
  • 2,342
  • 10
  • 23
-4

i did what you asked

import datetime
from datetime import date, datetime
import boto3
import json

client = boto3.client('lex-models')

response = client.get_utterances_view(
    botName='CreateServicesBot',
    botVersions=[
        '$LATEST',
    ],
    statusType='Missed'
)
response[lastUtteredDate] = response[lastUtteredDate].strftime("%Y-%m-%d 
%H:%M:%S")
response[firstUtteredDate] = response[firstUtteredDate].strftime("%Y-%m-%d 
%H:%M:%S")


with open('/tmp/output.json', 'w') as data:
    json.dump(response,data)


with open('/tmp/output.json') as f:
    data = json.load(f)
ustr=data["utteranceString"]
print ustr

and i got this error

NameError: name 'lastUtteredDate' is not defined

when i print response i got this (the first block)

{u'utterances': [{u'utterances': [{u'count': 49, u'utteranceString': u'hello', >u'lastUtteredDate': datetime.datetime(2018, 6, 7, 9, 44, 38, 146000, >tzinfo=tzlocal()), u'distinctUsers': 42, u'firstUtteredDate': > > >datetime.datetime(2018, 5, 31, 8, 52, 34, 907000, tzinfo=tzlocal())},

Beastn
  • 1
  • 1
  • 1
  • 2