python - 将 JSON 插入 MySQL

标签 python mysql json

我是 python 新手,正在尝试弄清楚如何将一些 json 插入 mysql 中。我正在运行一个已经有的 shell 脚本,它输出 json。

balance = subprocess.check_output([shell_script, 'all'])

conn = MySQLdb.connect(all my info)
cursor = conn.cursor()

#ive tried a few different things but this is the last one i tried
for i in balance.items():
term = i[0]
urls = json.dumps(i[1])
sql = """INSERT INTO balance (name, balance) VALUES (%s, %s)"""
cursor.execute(sql, (term, urls))

但是我尝试的一切我都得到了

AttributeError: 'str' object has no attribute 'items'

这是 shell 脚本的输出

{
"" : 52,
"bob" : 12,
"john" : 2,
"peter" : 4
}

最佳答案

subprocess.check_output() 的输出始终是一个字符串,但您似乎期望它是一个字典:

balance = subprocess.check_output([shell_script, 'all'])

# ...

for i in balance.items():

首先从命令的 JSON 输出加载对象:

balance = subprocess.check_output([shell_script, 'all'])
balance = json.loads(balance)

conn = MySQLdb.connect(all my info)
cursor = conn.cursor()

sql = """INSERT INTO balance (name, balance) VALUES (%s, %s)"""

for term, urls in balance.items():
    cursor.execute(sql, (term, urls))

无需再次将 urls 整数转储为 JSON。

关于python - 将 JSON 插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515210/

相关文章:

python - 如何使用 RecursionError(Python, PyQt4) 改善我的情况?

python - 在sqlite3中存储python日期

mysql - MySQL : #1452 上的奇数 IntegrityError

javascript - 地理位置:按接近度过滤

ajax - 在 Chrome 中使用本地文件的 jQuery getJSON 问题

python - 将查询集转换为包含 JSON 值的字典

python - 在Python中检查文件校验和

C# 和 MySQL : Delete Exists

java - 使用Java.Thread向MySQL数据库插入数据安全吗?

python - 使用 pandas DataFrame 中的误差线和数据点绘制线图