【发布时间】:2017-10-15 12:32:37
【问题描述】:
我想监控 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
【问题讨论】:
-
嗨伙计,我认为您解析失败的主要问题是您调用的文件“CSV”(逗号分隔值)实际上是“TSV”(制表符分隔值)。