您的位置:首页 > 编程语言 > Python开发

【python】从MySQL中读取内容,存为json对象的列表

2015-09-17 11:52 399 查看
现在有数据存在MySQL中,需要把其中的数据存为json对象再进行解析,写了一个简单的python脚本以供参考,其中用了python的MySQLdb库

# !/usr/bin/python
# -*- coding:utf-8 -*-

import json,MySQLdb

def tableToJson(table):

try:
conn = MySQLdb.Connect(host='localhost',user='root',passwd='nsfocus',db='securitycontroller',port=3306)    #define connection object
cur = conn.cursor()
except:
print 'MySQL connect fail...'

sql = 'select * from %s' %table
cur.execute(sql)
data = cur.fetchall()
cur.close()
jsonData = []
for row in data:
#each row just like 'e4e580edfa0ed99ab9159f962df4da16   000081eb0e69212fdcc4005106529732    00:11:22:03:04:02   00:90:0b:2f:15:46   10.201.111.1    114.114.114.114 7170    53  0   0   [(00:00:00:1e:08:09:64:36,46)]  2014-12-04T13:19:45.981+08:00   2014-12-04T13:19:45.981+08:00'
result = {}    # temp store one jsonObject
result['globalFlowId'] = row[0]
result['flowId'] = row[1]
result['src_mac'] = row[2]
result['dst_mac'] = row[3]
result['src_ip'] = row[4]
result['dst_ip'] = row[5]
result['src_port'] = row[6]
result['dst_port'] = row[7]
result['pkg_count'] = row[8]
result['byte_count'] = row[9]
result['links'] = row [10]
result['createTime'] = row[11]
result['lastTime'] = row[12]
jsonData.append(result)
return json.dumps(jsonData)

if __name__ == '__main__':
jsonData = tableToJson('globalRecord')
f = open('jsonData.txt','w+')
f.write(jsonData)
f.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: