【问题标题】:Insert JSON into MySQL将 JSON 插入 MySQL
【发布时间】:2014-02-26 05:19:39
【问题描述】:

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

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
}

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

    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。

    【讨论】:

    • 好答案谢谢。工作中,如果允许我会在 9 分钟内接受。
    猜你喜欢
    • 2016-10-10
    • 2018-03-02
    • 2016-06-30
    • 2011-05-14
    • 2015-01-09
    • 1970-01-01
    • 2022-01-18
    • 2017-10-29
    • 2020-01-16
    相关资源
    最近更新 更多