【问题标题】:Convert mySql query result to json using python使用python将mySql查询结果转换为json
【发布时间】:2017-10-15 12:32:37
【问题描述】:

我想监控 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

【问题讨论】:

  • 嗨伙计,我认为您解析失败的主要问题是您调用的文件“CSV”(逗号分隔值)实际上是“TSV”(制表符分隔值)。

标签: python mysql json


【解决方案1】:

试一试,朋友-

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"
    }
]

【讨论】:

  • 如果您想直接从 MySQL 转到 JSON,您需要使用 PIP 拉下一个 MySQL 模块,然后使用 Python 执行该查询——我认为它是将返回一个元组列表。
  • 谢谢,爱德华。我更新了我的问题,向您展示我的 csv 文件的外观。我在期待 {Com_alter_db_upgrade: 0} 时将 { "Variable_name\tValue": "Com_alter_db_upgrade\t0" } 作为 json 获取。
  • 顺便说一句。我能够直接从 mysql 查询中成功提取 json。我将脚本发布在答案中以帮助未来的用户。
【解决方案2】:

Pandas 是非常灵活的数据库。你可以在这里下载:LINK

一旦你拥有它:

import pandas as pd
from pandas.io import sql
import sqlite3

conn = sqlite3.connect('example.db')
e = pd.read_sql('select * from my_table;',conn)
b = e.to_json()

print(b)

我正在使用 sqlite3,但我猜它对所有 sql 都是通用的。

还有一个函数:pd.read_sql_table 可以直接从表中读取,但是你需要炼金术。

【讨论】:

    【解决方案3】:

    发布我自己的问题的解决方案以帮助该页面的未来访问者:

    使用以下脚本将mySql查询输出的结果转换为JSON并保存到文件中。

    但在此之前安装 mySql 连接器:

    sudo pip install MySQL-python
    

    并使用以下脚本。

    import MySQLdb
    import json
    
    conn = MySQLdb.connect(host = "localhost", user="root", passwd="your_password_here")
    
    cursor = conn.cursor()
    cursor.execute("SHOW GLOBAL STATUS")
    
    rs = cursor.fetchall()
    
    result = dict(rs)
    
    with open('result.json', 'w') as f:
        json.dump(result, f)
    

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 2013-07-18
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      相关资源
      最近更新 更多