将Django中MySQL查询的结果转换为JSON

时间:2013-07-19 07:21:41

标签: django json

所以我使用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]]

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

3 个答案:

答案 0 :(得分:2)

JSON格式正确,但你要转储列表,你应该转储一个字典......比如:

myData = {'people': data}

json.dumps(myData)

重点在于:有效的json响应必须以花括号开头和结尾,所以为了提供有效的json,你必须将Python字典对象转储为“根对象”...换句话说,你需要至少一个带钥匙的物体。

来自http://json.org

  

JSON基于两种结构:

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

列表或关联数组。       有序的值列表。在大多数语言中,这被实现为数组,向量,列表或序列。

答案 1 :(得分:0)

from django.core import serializers

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

但是并非所有内容都可以像这样序列化为JSON,有些东西需要自定义encoder

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

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

您的数据库调用现在将是Winner.objects.all(),这将为所有获奖者提供

并带有计数

Winner.objects.annotate(wins=Count('name'))

答案 2 :(得分:0)

ProducerConfig values: 
    acks = 1
    batch.size = 16384
    bootstrap.servers = [localhost:9098]
    buffer.memory = 33554432
    client.id = 
    compression.type = none
    connections.max.idle.ms = 540000
    enable.idempotence = false
    interceptor.classes = null
    key.serializer = class org.apache.kafka.common.serialization.StringSerializer
    linger.ms = 0
    max.block.ms = 60000
    max.in.flight.requests.per.connection = 5
    max.request.size = 1048576
    metadata.max.age.ms = 300000
    metric.reporters = []
    metrics.num.samples = 2
    metrics.recording.level = INFO
    metrics.sample.window.ms = 30000
    partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner
    receive.buffer.bytes = 32768
    reconnect.backoff.max.ms = 1000
    reconnect.backoff.ms = 50
    request.timeout.ms = 30000
    retries = 0
    retry.backoff.ms = 100
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.mechanism = GSSAPI
    security.protocol = SSL
    send.buffer.bytes = 131072
    ssl.cipher.suites = null
    ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
    ssl.endpoint.identification.algorithm = null
    ssl.key.password = [hidden]
    ssl.keymanager.algorithm = SunX509
    ssl.keystore.location = /home/user/Desktop/Project/nlp-sogei-integration-ms/nlp-sip-docker/security/certs/docker.kafka.client.keystore.jks
    ssl.keystore.password = [hidden]
    ssl.keystore.type = JKS
    ssl.protocol = TLS
    ssl.provider = null
    ssl.secure.random.implementation = null
    ssl.trustmanager.algorithm = PKIX
    ssl.truststore.location = /home/user/Desktop/Project/nlp-sogei-integration-ms/nlp-sip-docker/security/certs/docker.kafka.client.truststore.jks
    ssl.truststore.password = [hidden]
    ssl.truststore.type = JKS
    transaction.timeout.ms = 60000
    transactional.id = null

2019-05-14 10:29:04.987 ERROR 15924 --- [nio-8080-exec-3] o.s.k.support.LoggingProducerListener    : Exception thrown when sending a message with key='1' and payload='Envelope [header=Header{transactionId='01', dealerCode=15155, messageId=200, competitionTypeCode=5, ...' to topic WFL_REQUEST:

org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.

2019-05-14 10:29:04.988  INFO 15924 --- [nio-8080-exec-3] i.sisal.nlp.sip.kafka.MockKafkaProducer  : send() - OUT