oladimeji
oladimeji

Reputation: 119

Python Django:JSONDecodeError when i try to retrieve data from the api

When I tried to return a date in my python api request, I get the error message 'Object of type date is not JSON serializable'. I converted it to JSON using this function below:

    def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()

Now it is returning a null value and also the error message .

'JSONDecodeError at /search/ Expecting value: line 1 column 1 (char 0)'

What am i doing wrongly?This is my code below:

    new_parameter=json.dumps(parameters, default = myconverter)
    print(new_parameter)

    urls = 'https://ije-api.tcore.xyz/v1/flight/search-flight'

    result = requests.post(urls,json=new_parameter,headers=headers).json()
            print(result.text)

    flight ={
                "departure_date": result['body']['data']['itineraries'][0]['origin_destinations'][0]['segments'][0]['departure']['date'],
                "departure_time": result['body']['data']['itineraries'][0]['origin_destinations'][0]['segments'][0]['departure']['time'], 



            }
     print(result)

Upvotes: 0

Views: 151

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can specify a custom encoder by creating a subclass of json.JSONEncoder, you need to return/call super of the default method to encode regular JSON serializable objects

class DatetimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        return super(DecimalEncoder, self).default(o)

new_parameter=json.dumps(parameters, cls=DatetimeEncoder)

Upvotes: 1

Related Questions