0

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@lain. I am still getting 'JSONDecodeError at /search/ Expecting value: line 1 column 1 (char 0)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.