Python django simplejson抛出键必须是字符串错误
这个错误听起来很简单,但我无法修复。我试着在字典里修改,但我哪儿也不去,我想也许这里的人能帮我指出我需要做些什么来解决这个问题。下面是我的代码Python django simplejson抛出键必须是字符串错误,python,django,Python,Django,这个错误听起来很简单,但我无法修复。我试着在字典里修改,但我哪儿也不去,我想也许这里的人能帮我指出我需要做些什么来解决这个问题。下面是我的代码 blog_calendar = BlogI18n.objects.filter(language=request.LANGUAGE_CODE, blog__published_at__gte=datetime(year, month, 1),
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__())
转换其返回类型时,当我注释掉以下行时,Error无法转换为json(键必须是字符串)
calendar_response['events'].append(dict((i.blog.published_at.date(), (i.blog.slug, i.title)) for i in blog_calendar))
它是有效的,所以问题在于,你知道我如何以simplejson能够理解的方式重建我的字典吗
关于,您必须将所有键转换为字符串 在这方面:
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())
或:
您必须将所有键转换为字符串 在这方面:
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())
或:
或者,如果希望日期采用特定格式,可以使用strftime,例如:
i.blog.published_at.date().strftime(“%Y-%m-%d”)
分别以年、月、日表示的结果。或者,如果您希望以特定格式显示日期,可以使用strftime,例如:
i.blog.published_at.date().strftime(“%Y-%m-%d”)
将分别在年、月、日产生什么结果