python讀取mysql返回json


python內部是以tuple格式存儲的關系型數據庫的查詢結果,在實際的使用過程中可能需要轉換成list或者dict,json等格式。在這里講解如何將查詢的結果轉成json字符串。這里需要導入numpy、pandas、json包

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 
 5 import json
 6 import numpy as np
 7 import pandas as pd
 8 
 9 import AppSetting.dbConfig as db
10 
11 try:
12     sql = "select * from el_catalog where parentid='0' order by itemorder";
13     df = pd.read_sql(sql, db.pd_connect + 'yw_collection')
14     # 獲取列名
15     column_list = list(df.columns)
16     df1 = np.array(df)
17 
18     lst = []
19     for row in df1:
20         # 循環每一行數據,組裝成一個字典,然后得到字典的列表
21         lst.append(dict(zip(column_list, list(row))))
22         # 導入json,將列表轉為json字符串
23         # son.dumps序列化時候對中文默認使用的ascii編碼,想要輸出真正的中文需要指定ensure_ascii=False
24         str1 = json.dumps(lst, ensure_ascii=False)
25     print(str1)
26 except Exception as ex:
27     print(ex)

查詢結果:

  [{"Id": 1, "Name": "人員", "ParentId": "0", "ItemOrder": 1}, {"Id": 2, "Name": "企業", "ParentId": "0", "ItemOrder": 2}, {"Id": 3, "Name": "工程", "ParentId": "0", "ItemOrder": 3}]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM