Метание ключей в django simplejson должно быть ошибкой строки - PullRequest
0 голосов
/ 02 августа 2011

ошибка звучит очень прямо, но я не могу ее исправить.Я попытался измениться в своем словаре, но никуда не собираюсь, и подумал, может, кто-то здесь может помочь мне указать, что мне нужно сделать, чтобы решить эту проблему.Ниже приведен мой код

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

при преобразовании возвращаемой ошибки TypeError, которая не может быть преобразована в json (ключи должны быть строкой), когда я закомментирую следующую строку

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

, она работает, поэтомупроблема в том, есть ли какая-нибудь идея, как я могу перестроить свой словарь так, чтобы простой человек мог его понять?

с уважением,

Ответы [ 2 ]

3 голосов
/ 02 августа 2011

Вы должны преобразовать все свои ключи в строки.

В этой строке:

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()
1 голос
/ 02 августа 2011

Или, если вы хотите иметь дату в определенном формате, вы можете использовать strftime, например:

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

что приведет к соответственно году, месяцу и дню.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...