2011-08-02 4 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으로 변환 할 형식 오류없는 반환 변환 (키 문자열이어야합니다), 그래서 문제에 이 간단한 생각이 내 사전을 어떻게 재구성 할 수 있겠 어?

안부,

답변

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() 표현이다. 당신은, 당신은 예를 들어,의 strftime을 사용할 수있는 특정 형식의 날짜를하려는 경우,

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

또는 :

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

또는 : 예를 들어 같은 문자열을 반환 뭔가를 대체

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

결과는 각각 연, 월, 일이됩니다.