Search code examples
pythonjsonyaml

Converting yaml to json:TypeError: Object of type 'date' is not JSON serializable


I need to convert a yaml file to json. However I get the error

TypeError: Object of type 'date' is not JSON serializable

I checked other posts and tried to incorporate the suggestions but nothing seems to work. Here is what I have

import yaml
import json
import datetime

def DateEncoder(obj):
        if isinstance(obj, datetime.datetime):  
            return obj.strftime('%Y-%m-%d')  

with open('./660093.yaml') as f:
    print(json.dumps(yaml.load(f), default=DateEncoder))

TypeError: Object of type 'date' is not JSON serializable

When I checked the contents of the yaml file I see 2 lines with date in the following format

{'meta': {'data_version': 0.9, 'created': datetime.date(2013, 12, 20), 
'revision': 1}, 'info': {'city': 'Abu Dhabi', 'dates': [datetime.date(2013, 11, 15)], 
'gender': 'male', 'match_type': 'IT20', 'neutral_venue': 1, 'outcome': 
{'by': {'runs': 32}, 'winner': 'Ireland'}, 'overs': 20,
...
...

Any help will be appreciated


Solution

  • Your DateEncoder only handles datetime objects, not date objects. That's your problem.

    Change it like this:

    def DateEncoder(obj):
      if isinstance(obj, (datetime.datetime, datetime.date)):
          return obj.strftime('%Y-%m-%d')