json.dumps给我AttributeError:'str'对象没有属性'get'

时间:2018-11-16 00:10:07

标签: python pythonanywhere

我收到此错误消息:

 <a href="#" onClick="return false;">

我知道触发错误的是我的json.dumps。这是我的代码:

AttributeError: 'str' object has no attribute 'get'

检查第一个功能的结尾。那是我做退货的地方。我还以为我的字典格式错误,但是我检查了一下,看起来不错:

from django.http import HttpResponse
import os
import datetime
import json

SUNDAY = 6
SATURDAY = 5

weekdayBookingTimes = ["10:00","10:30","11:00","11:30","12:00", "12:30", "13:00","13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"]

def sendBookingForDate(request):
    dateToFetchBookings = request.GET.get('date','')
    #Check if date is SUNDAY
    if checkDayOfWeek(dateToFetchBookings) == SUNDAY:
        pass

    #Check if day is Saturday
    elif checkDayOfWeek(dateToFetchBookings) == SATURDAY:
        if os.path.isfile((dateToFetchBookings+".txt")):
            pass #tbt
        else:
            createBookingsForSaturday(dateToFetchBookings)
    #Check if day is normal day
    else:
        if os.path.isfile(dateToFetchBookings+'.txt'):
            pass
        else:
            createBookingsForNormalDays(dateToFetchBookings)

    with open('/home/MScissorss/mysite/mysite/'+dateToFetchBookings+'.txt') as f:
        bookingsToSend = json.load(f)
    #return HttpResponse(dateToFetchBookings)
    return json.dumps(bookingsToSend)


def checkDayOfWeek(date):
    tempDateStorage = date.split('-')

    year = int(tempDateStorage[0])
    month = int(tempDateStorage[1])
    day = int(tempDateStorage[2])

    return datetime.datetime(year,month,day).weekday()


def createBookingsForSaturday(date):

    normalBookings = {}

    for x in range(0,11):
        normalBookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}

    with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
        file.write(json.dumps(normalBookings))

def createBookingsForNormalDays(date):
    #Test data

    bookings = {}

    for x in range(0,17):
        bookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}

    with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
        file.write(json.dumps(bookings))

在json.dumps上方注释的返回效果很好。运行该程序时我没有任何错误。对可能是什么问题有任何想法吗?

更新-已添加完整追溯

{
"0": {"bookingTime": "10:00", "booked": "false", "bookieName": "", "bookieNumber": ""},
"1": {"bookingTime": "10:30", "booked": "false", "bookieName": "", "bookieNumber": ""}, 
"2": {"bookingTime": "11:00", "booked": "false", "bookieName": "", "bookieNumber": ""}, 
"3": {"bookingTime": "11:30", "booked": "false", "bookieName": "", "bookieNumber": ""}
}

1 个答案:

答案 0 :(得分:0)

正如@Barmar在评论中指出的那样。我需要做的就是将我的回报从return json.dumps(bookingsToSend)更改为return JsonResponse(bookingsToSend)