2017-01-07 11 views
0

私は小さなジレンマに陥っています。私はテーブルからリストを取得するPythonのバージョン2.7モジュールMySQLdbを使用しています。コードは、これまでのところ非常に簡単です:PythonからJSONへのMySQLdbからの選択リストのフォーマット

#!/usr/bin/python 
import json 
import MySQLdb 

db_host = "localhost" 
db_user = "xxx" 
db_passwd = "yyy" 
db_table = "table" 

try: 
     db = MySQLdb.connect(host=db_host, user=db_user, passwd=db_passwd, db=db_table) 
     cursor = db.cursor(MySQLdb.cursors.DictCursor) 
     cursor.execute("""SELECT serial, registered_id FROM devices WHERE registered_id IS NOT NULL AND registered_id <>''""") 
     devices = cursor.fetchall() 
     print devices 
except: 
     print "Something went wrong with the MySQL" 

印刷こののように出てくる:

(( '00000000762c1d3c'、 '019')、( '000000003ad192f2'、 '045')、(私は、これは番目のように、JSONに正しく解析されるようにリストしてもらうにはどうすればよい「000000004c9898aa」、「027」))

(それはかなり長いだったので、私はそれを下に短縮。)

で、それは次のようになります。

for row in devices: 
     print "%s, %s" % (row["serial"], row["registered_id"]) 

私は彼らに、それぞれを印刷することができるよ:

{ 
      "device": 
       [ 
        { "serial": "00000000762c1d3c", "registered_id": "019" }, 
        { "serial": "000000003ad192f2", "registered_id": "045" }, 
        { "serial": "000000004c9898aa", "registered_id": "027" }, 
       ] 
     } 

私はDictCursorsとcorespondenceでこれを追加することによってことを考え出しました。しかし、私はまだJSONを適切に構造化する方法を見つけることができません。

ありがとうございます。

答えて

1

DictCursorは物事がはるかに簡単になるかもしれない:

import json 

db = MySQLdb.connect(host=db_host, 
        user=db_user, 
        passwd=db_passwd, 
        db=db_table, 
        cursorclass=MySQLdb.cursors.DictCursor) 
cursor = db.cursor() 
cursor.execute("""SELECT serial, registered_id FROM devices WHERE registered_id IS NOT NULL AND registered_id <>''""") 
devices = cursor.fetchall() 

data = {"device": list(devices)} 

# dump to a json file 
with open("output.json", "w") as f: 
    json.dump(data, f) 
関連する問題