将JSON插入MySQL

时间:2014-02-02 19:35:15

标签: 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
}

1 个答案:

答案 0 :(得分:2)

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。