简体   繁体   中英

django view pass json to javascript

I try to pass json to javascript. I want make json like this

data: [            
            {
            value: 335,
            name: 'Coding'
            }, {
            value: 310,
            name: 'Database'
            }, {
            value: 234,
            name: 'UIX'
            }, {
            value: 135,
            name: 'Manajemen'
            },]
          }]

I want make json like this, so I can put to javascript

 {
                value: 335,
                name: 'Coding'
                },

And this is my code

cursor.execute('SELECT u.nama_ktgu, COUNT(m.nim) as jml FROM mahasiswa_mhs_si m, mata_kuliah_kategori_utama u, mata_kuliah_kategori k WHERE k.kode_ktgu_id = u.id AND m.kode_ktg_id = k.id  GROUP BY k.id')
    ktg_mhs = cursor.fetchall()

    #JSON CHART
    chart_ktg = {}
    for i in ktg_mhs:       
        chart_ktg['value'] = ktg_mhs[i][1]
        chart_ktg['name'] = ktg_mhs[i][0]
    
    json = json.dumps(chart_ktg)

use this:

import json

ktg_mhs = (
    (1,2),
    (3,4),
    (5,6),
)

#JSON CHART
result = []
for i in ktg_mhs:
    chart_ktg = {
        'value': i[1],
        'name': i[0]
    }
    result.append(chart_ktg)

json = json.dumps(result)

print(json)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM