2011-08-02 8 views
0

でなければなりません。エラーは非常に単純ですが、修正できません。私は辞書を変更しようとしましたが、どこにも行かないので、ここにいる誰かが私がそれを解決するために必要なことを指摘するのに役立つかもしれないと思いました。以下は、私のコードは、私は次の行django simplejsonを投げるキーは文字列エラー

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

それが動作をコメントアウトするとき

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に変換することはTypeErrorができないの復帰変換(キーは文字列でなければならない)ので、問題がですこれは、どのように私はsimplejsonそれを理解する方法で私の辞書を再構築することができます任意のアイデア?

について、

答えて

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

それとも、あなたが特定の形式で日付を持っているしたい場合は、例えば、strftimeのを使用することができます。

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

それぞれ、年、月、日になるもの

関連する問題