django simplejson 报错:键必须是字符串

0 投票
2 回答
1610 浏览
提问于 2025-04-16 22:45

这个错误听起来很简单,但我就是无法解决。我尝试在我的字典里做一些修改,但没有任何进展。我想也许这里有人能帮我指出我该怎么做才能解决这个问题。下面是我的代码:

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__())

在转换的时候,它返回了一个类型错误,提示无法转换为json(键必须是字符串)。当我把以下这一行注释掉时:

    calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))

它就能正常工作,所以问题出在这里。有没有什么办法可以让我重新构建我的字典,让simplejson能够理解呢?

谢谢,

2 个回答

1

或者,如果你想要以特定的格式显示日期,可以使用strftime这个方法,比如:

i.blog.published_at.date().strftime('%Y-%m-%d')

这样做的结果会分别显示年份、月份和日期。

3

你需要把所有的键都转换成字符串。

在这一行:

calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))

问题出在 i.blog.published_at.date() 这个表达式上。把它换成一个返回字符串的东西,比如:

str(i.blog.published_at.date())

或者:

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

撰写回答