我想监控 mySql 数据库以获取其性能更新,因此我执行了一个查询 show global status;
这为我提供了一个变量列表,例如 Uptime、aborted_connections
等.
但是我想把结果导出成json格式,可以用python脚本实现吗?
到目前为止,我所做的是,
- 将查询结果导出到 .csv 文件。
- 尝试使用以下 python 代码将该 csv 文件转换为 json
import csv import json csvfile = open ('./tempp/op.csv','r') jsonfile = open('./tempp/op.json','w') fieldnames = ("Variable_name","Value") reader = csv.DictReader(csvfile,fieldnames) for row in reader: json.dump(row,jsonfile) jsonfile.write('\n')
问题:
- 上面的脚本没有给出预期的结果。它生成的 json 类似
{"Value": null, "Variable_name": "Variable_name\tValue"} {"Value": null, "Variable_name": "Aborted_clients\t0"} {"Value": null, "Variable_name": "Aborted_connects\t7"} {"Value": null, "Variable_name": "Binlog_cache_disk_use\t0"} {"Value": null, "Variable_name": "Binlog_cache_use\t0"} {"Value": null, "Variable_name": "Binlog_stmt_cache_disk_use\t0"} {"Value": null, "Variable_name": "Binlog_stmt_cache_use\t0"}
- 首先将结果写入文件然后从中读取数据似乎是一种糟糕的方法。有没有更好的方法直接将mySql查询的结果直接转换为json对象?
Edit
根据答案:
我的 op.csv 文件如下所示:
Variable_name Value
Aborted_clients 0
Aborted_connects 7
Binlog_cache_disk_use 0
Binlog_cache_use 0
Binlog_stmt_cache_disk_use 0
Binlog_stmt_cache_use 0
Bytes_received 31075
Bytes_sent 1891186
Com_admin_commands 445
Com_assign_to_keycache 0
Com_alter_db 0
Com_alter_db_upgrade 0
最佳答案
试一试伙计-
import csv
import json
rows = []
with open('test.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
rows += [row]
print json.dumps(rows, sort_keys=True, indent=4, separators=(',', ': '))
json.dumps 中的参数只是为了让输出的格式很好。
因此,对于以下输入-
Heading1,Heading2,Heading3
Row1Value1,Row1Value2,Row1Value3
Row2Value1,Row2Value2,Row2Value3
Row3Value1,Row3Value2,Row3Value3
你应该得到这个-
[
{
"Heading1": "Row1Value1",
"Heading2": "Row1Value2",
"Heading3": "Row1Value3"
},
{
"Heading1": "Row2Value1",
"Heading2": "Row2Value2",
"Heading3": "Row2Value3"
},
{
"Heading1": "Row3Value1",
"Heading2": "Row3Value2",
"Heading3": "Row3Value3"
}
]
关于python - 使用python将mySql查询结果转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001245/