将mysql查询结果(对象数组)转换为json

时间:2018-09-18 14:59:53

标签: python

我要从mysql查询结果转换。

DealerID | Dealer Name | SubDealerID | Subdealer Name
AL06        A L A S K A      0001       A L A S K A JKT
AL06        A L A S K A      AG01       AGUS SANTOSO,BPK.
AL06        A L A S K A      IM01       IMPERIAL, TOKO
AL09      ALFA ELECTRONIC    0001       ALFA ELECTRONIC
AL09      ALFA ELECTRONIC    AN01       ANGGA MUHAMAD SOLEH
AL09      ALFA ELECTRONIC    ER01       ERWIN KURNIAWAN
AL10         PT.ALFA         0001       PT.ALFA RETAILINDO       TBK
AL10         PT.ALFA         AL01       PT. ALFA RETAILINDO TBK
AL10         PT.ALFA         AL02       PT.ALFA RETAILINDO TBK     DPK
AL10         PT.ALFA         AL03       PT.ALFA RETAILINDO TBK     STR
AL10         PT.ALFA         AL04       PT.ALFA RETAILINDO TBK
AL10         PT.ALFA         AL05       PT.ALFA RETAILINDO  TBK    KBY

我需要使用python flask转换为这种json格式:

{
        "data":
        {
                "dealerID": "AL06",
                "dealer": "A L A S K A",
                "sdealer" : [
                        { "sdi": "AG01","sdealer": "AGUS SANTOSO,BPK."},
                        { "sdi": "IM01","sdealer": "IMPERIAL, TOKO"}
                        ]
         }
    }

有人可以帮我吗,谢谢

1 个答案:

答案 0 :(得分:0)

也许我做得不好。但是我已经尽力了,这是我的主意:

jsons   = {"data":[]}
det     = {} # use to check if have same id
#query() return cursor.fetchall()
for p in query("select * from temp"):
    if p[0] in list(det.keys()):
        jsons["data"][ det[ p[0] ] ]["sdealer"].append({ "sdi": p[2],"sdealer": p[3]})
    else:
        form      = { "dealerID":p[0],
                  "dealer":p[1],
                  "sdealer":[
                    { "sdi": p[2],"sdealer": p[3]}
                    ]}
        det[p[0]] = 0 if det == {} else list(det.values())[-1] + 1
        jsons["data"].append(form)
print(jsons)