以特殊方式从数据库获取json

时间:2019-05-08 20:00:14

标签: python mysql json

我使用python和mysql.connector 这是我的代码

 mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table")
myresult = mycursor.fetchall();
json_data=[] 
for x in myresult:
    json_data.append(x)
print(json.dumps(json_data))# CREATE JSON

得到我的结果:

[[1, 61, 8585, "80000000"], [3, 61, 5151, "200"], [4, 61, 8585, "20"]]

但是我需要这个:

{
    "data": [
        {
            "id": "1",
            "sample": "61",
            "Price": "80000000",
            "name": "----"
        },
        {
            "id": "3",
            "sample": "61",
            "Price": "200",
            "name": "ali"

        }
    ]
}

我该怎么办? 感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

您将不得不编写另一个函数,将您的sql输出解析为json格式。像这样的东西:

def json_parser(sql_data):
    data_dict = {}
    list_of_rows = []
    for record in sql_data:
       dict1 = {}
       dict1['id'] = record[0] 
       dict1['sample'] = record[1] 
       dict1['Price'] = record[2]
       dict1['name'] = record[3]
       list_of_rows.append(dict1)
    data_dict['data'] = list_of_rows