将新字段附加到响应json

时间:2018-03-04 09:55:35

标签: python

我有这个问题

line 192, in getstatbygroup
    json_data[i].append(dict({'total': percent}))
TypeError: list indices must be integers or slices, not dict

,我找到了其他答案,并了解我有词典列表。但是我无法理解我应该怎样做才能得到正确的结果。我需要为每个人添加“总计”字段。

 json_data=[]
    cursor.execute(...)
    query= cursor.fetchall()
    row_headers=[x[0] for x in cursor.description]
    for result in query:
        json_data.append(dict(zip(row_headers,result)))
    json_datamy = json.dumps(json_data,ensure_ascii = False)
    json_datamy1 = json.loads(json_datamy)
    for i in json_data:
        results = [int(i) for i in json_datamy1[0]['stats']]
        percent = sum(results)/float(len(results))*100
        json_data[i].append(dict({'total': percent}))
    return jsonify(json_data)

响应:

 [
        {
            "here": 0,
            "id_student": 1,
            "last_name": "name",
            "name": "Liya",
            "schedules": "4",
            "stats": "0",
            "surname": "name"
        },
        {
            "here": 0,
            "id_student": 2,
            "last_name": "name",
            "name": "name",
            "schedules": "4",
            "stats": "0",
            "surname": "name"
        }
    ]

0 个答案:

没有答案