python - 使用python将mySql查询结果转换为json

标签 python mysql json

我想监控 mySql 数据库以获取其性能更新,因此我执行了一个查询 show global status; 这为我提供了一个变量列表,例如 Uptime、aborted_connections 等.

但是我想把结果导出成json格式,可以用python脚本实现吗?

到目前为止,我所做的是,

  1. 将查询结果导出到 .csv 文件。
  2. 尝试使用以下 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')

问题:

  1. 上面的脚本没有给出预期的结果。它生成的 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"}
  1. 首先将结果写入文件然后从中读取数据似乎是一种糟糕的方法。有没有更好的方法直接将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/

相关文章:

python - 尝试写入字典中的特定键,但它正在写入整个字典中的所有键

python3.5 : asyncio, 如何等待 "transport.write(data)"完成或返回错误?

mysql - 如何在mysql中查询重复的字符串条目

mysql - sql教程脚本错误

mysql - SQL - 如果某事为真,如何输出带有二进制指示符的结果集?

ios - 使用 AFNetworking 将 JSON 解析为 NSDictionary

python - Windows 上 Python 中的长路径

python - Python中有 '?'控制流吗?

ios - JSON 到 NSMutableArray(Xcode 中的 Swift)

javascript - 如何在服务器端读取ajax json数据