如何从数据库json格式解析数据

时间:2015-04-14 10:14:22

标签: javascript jquery python json

我想在HTML页面中显示我的json的内容 我在数据库中读取了我的表格,我把它们放在一个列表中然后我试着解析json格式,但问题是我试图从json中检索一些数据我不能通过例如我想要显示名称或类似的东西

@APP.route('/scan',methods=['GET'])
def scan():
    listscan = []
    con = mdb.connect('localhost','testuser', 'test623', 'bd')
    cur = con.cursor()
    cur.execute("SELECT * FROM tablesd")
    rows = cur.fetchall()
    for row in rows:
        chaine = "Id:" + str(row[0]) + ',' + "HOST_NAME:" + str(row[1]) + "," + "ADDRESS:" + str(row[2]) + "," + "IP:" + str(row[3]) + "," + "TIME:" + str(row[4]) + "," + "DATE:" + str(row[5]) + "," + "CONN:" + str(row[6]) + "," + "ETAT:" + str(row[7]) + "," + "NEWgh:" + str(row[8])
    listscan.append(chaine)

    print json.dumps(listscan)
    return json.dumps(listscan)
function scan (){ 
    $.ajax({
        type: 'GET',
        url: '/scan',
        dataType: 'json',
        success: function(json) {
            alert('ok');
            var lang = '';
            $.each(json, function() {
                lang += this['Id'] + "<br/>";
            });
            $("#donnees").html(lang);
        },
        error: function() {
            alert('La requête n\'a pas abouti');
        }
    });    
}

print json.dumps(listscan)的结果:

  

[&#34; ID:1,HOST_NAME:,地址:X:X:X:X:X:X,IP:172.xxx,时间:17:25,DATE:04/04/15中,CONN :0,ETAT:null,NEWgh:1&#34;,&#34; Id:2,HOST_NAME :, ADDRESS:Y:Y:Y:Y:Y:Y,IP:192.xxx,TIME:17:25 ,DATE:04/04/15中,CONN:0,ETAT:空,NEWgh:1&#34;]

我喜欢显示undefined我没有收到id。

1 个答案:

答案 0 :(得分:1)

您应该更新您的回复(listscan),如:

var json = [
 {'Id':1, HOST_NAME:'', ADDRESS:'x:x:x:x:x:x', IP:'172.x.x.x', TIME:'17:25', DATE:'04/04/15', CONN:0, ETAT:null, NEWgh:1},
 {'Id':1, HOST_NAME:'', ADDRESS:'x:x:x:x:x:x', IP:'172.x.x.x', TIME:'17:25', DATE:'04/04/15', CONN:0, ETAT:null, NEWgh:1},
];

$.each(json, function() {
    $('body').append(this['Id'] + '<br\>');
});

您可以在此处找到一个示例:http://jsfiddle.net/guilhermeaferreira/jm86qr0v/