0

所以我使用 mySQL 查询来查询我的数据库,如下所示:

    cursor = connection.cursor()
    cursor.execute("select winner,count(winner) as count from DB")
    data = cursor.fetchall()

现在我想以 JSON 格式将数据表发送到我的应用程序(作为 GET 请求)。这样做不会发送格式正确的 JSON 响应,我无法在客户端解析它。

    return HttpResponse(json.dumps(data), content_type='application/json;charset=utf8')

json.dumps(data) 返回:

    [["John Doe", 45]]

在这方面的任何帮助将不胜感激。

4

3 回答 3

2

The JSON is properly formatted, but you are dumping a list, you should dump a dictionary instead... something like:

myData = {'people': data}

json.dumps(myData)

The point is this: a valid json response must start and end with curly braces, so in order to serve a valid json you have to dump a Python dictionary object as a "root object"... in other words you need at least an object with a key.

From http://json.org

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed

list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

于 2013-07-19T07:29:20.473 回答
0
from django.core import serializers

json_data = serializers.serialize('json', data)
return HttpResponse(json_data, mimetype='application/json')

然而并不是所有的东西都可以像这样序列化成 JSON,有些东西需要自定义编码器

您应该使用模型和 ORM,而不是编写自己的 SQL。您可以轻松地将您的语句转换为这个简单的模型和简洁的 ORM 调用。

class Winner(models.Model):
   name = models.CharField()

你的数据库调用现在Winner.objects.all()将给所有获胜者

并与计数

Winner.objects.annotate(wins=Count('name'))
于 2013-07-19T07:26:46.767 回答
0
from django.http import JsonResponse
from django.db import connections
from django.http import HttpResponse
import json

def testRawQuery(request):
    cursor = connections['default'].cursor()
    cursor.execute("select winner,count(winner) as count from DB")
    objs = cursor.fetchall() 
    json_data = []
    for obj in objs:
        json_data.append({"winner" : obj[0], "count" : obj[1]})
    return JsonResponse(json_data, safe=False)
于 2019-05-14T08:45:06.403 回答