小白求教,这种 json 怎么用 python 解析成参数数组插入 mysql 当中?

2015-05-11 12:52:17 +08:00
 miaomiaomiaoa

初学python的小白
json文件如下:
[
{
"_id": "55501245ef21cb978435bdb0",
"index": 0,
"guid": "316f9bb8-1e0e-4b02-ad41-bc2e65966a26",
"balance": "$1,115.97",
"age": 34,
"eyeColor": "brown",
"name": "Manning Schroeder",
"gender": "male",
"about": "Commodo cupidatat occaecat aliquip mollit deserunt fugiat ad sint magna ex anim nisi deserunt anim. Nulla laborum excepteur velit ad sit adipisicing esse minim. Pariatur aliquip reprehenderit adipisicing cupidatat anim labore minim ut.\r\n",
"tags": [
"exercitation",
"amet",
"quis",
"consequat"
],
"friends": [
{
"id": 0,
"name": "Mandy Erickson"
},
{
"id": 1,
"name": "Lang Cooper"
},
{
"id": 2,
"name": "Hill Alvarado"
}
],
"greeting": "Hello, Manning Schroeder! You have 1 unread messages.",
"favoriteFruit": "banana"
},

我现在能会读单个元素,但是在拼接字符串的时候,总是出错,球大神解答。
我的代码如下:
import json,pprint
with open('/Users/xxxosx/Downloads/1.json','r') as jf:
jdata = json.load(jf)
content = 'insert into xxx values'
for i in jdata:
a= {i["_id"],",",i["index"],",",i["guid"],",",i["isActive"],",",i["balance"],i["picture"],i["age"],i["eyeColor"],
i["name"],i[blahblah]}
content =content.join(a)
print content
for j in range(3):
print i["friends"][j]["id"],i["friends"][j]["name"]

3664 次点击
所在节点    Python
5 条回复
Septembers
2015-05-11 12:53:12 +08:00
建议你去玩MongoDB(我是来歪楼的
miaomiaomiaoa
2015-05-11 13:06:12 +08:00
@Septembers 。。我是玩oracle11g得。。
fangjinmin
2015-05-11 13:13:23 +08:00
a=[i["_id"],i["index"],i["guid"],i["isActive"],i["balance"],i["picture"],i["age"],i["eyeColor"],
i["name"],i[blahblah]]
content = content + "(" + ",".join(a) + ")"
fzinfz
2015-05-11 20:37:11 +08:00
为了LZ的视力着想,建议以后不要string join了,改用%s吧~

范例: http://mysql-python.sourceforge.net/MySQLdb.html

c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
] )
fzinfz
2015-05-11 20:41:11 +08:00
这有个更好的: http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html


add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}

cursor.execute(add_salary, data_salary)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/190136

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX