【问题标题】:get json from database In a special way以特殊方式从数据库中获取json
【发布时间】:2019-09-26 15:04:03
【问题描述】:

我使用 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"

        }
    ]
}

我能做什么? 感谢您的帮助:)

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

    您必须编写另一个函数,将您的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 2017-08-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2016-12-08
      相关资源
      最近更新 更多