Q:

django simplejson throwing keys must be a string error

the error sounds very straight forward but am unable to fix it. I tried changing in my dictionary but am not going anywhere and I thought maybe someone in here can help me point out what I need to do to solve it. Below is my code 
blog_calendar = BlogI18n.objects.filter(language=request.LANGUAGE_CODE,
                                        blog__published_at__gte=datetime(year, month, 1),
                                        blog__published_at__lte=datetime(year, month, calendar.monthrange(year, month)[1])
                                        ).order_by('-blog__published_at').select_related()

try:
    calendar_response = {}
    calendar_response['properties'] = []
    calendar_response['properties'].append({'next_url' : reverse('blog-archives-month-year',
                                                                 args=[(date(year, month, 1)-timedelta(days=31)).year, (date(year, month, 1)-timedelta(days=31)).month])}
    )
    calendar_response['properties'].append({'prev_url' : reverse('blog-archives-month-year',
                                                                 args=[(date(year, month, 1)+timedelta(days=31)).year, (date(year, month, 1)+timedelta(days=31)).month])}
    )
    calendar_response['current_month'] = []
    calendar_response['current_month'].append({'month':'%s, %s' % (calendar.month_name[month], year)})
    calendar_response['events'] = []
    if blog_calendar:
        calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))
    else:
        calendar_response['events'].append(None)
except Exception, e:
    print e.__str__()

if  request.is_ajax():
    # try converting the dictionary to json
    try:
        from django.core.serializers.json import DjangoJSONEncoder
        return HttpResponse(simplejson.dumps(calendar_response, cls=DjangoJSONEncoder), 
                            mimetype="application/json")
    except Exception, e:
        return HttpResponse(e.__str__())

when converting its returning TypeError unable to convert to json (keys must be a string) when I comment out the following line
    calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))

it works, so the problem is in this, any idea how i can rebuild my dictionary in a way that the simplejson would understand it?
regards,

A:

You have to convert all your keys to strings.
In this line:
calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))

The culprit is the i.blog.published_at.date() expression. Substitute it with something which returns a string, as for example:
str(i.blog.published_at.date())

or:
i.blog.published_at.date().isoformat()

