我是 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/