d={
"state": "ok",
"errmsg": "",
"data": {
"id": 1,
"username": '李元霸'
}
}
}
}
for i in d['data']:
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='test', charset='utf8')
cursor = conn.cursor()
tsql = "insert into test1(id,name)values(%s,'%s')" % (i['id'],i['username'])
print(tsql)
cursor.execute(tsql)
conn.commit()
conn.close()
这种我会处理存入 但是加key就不知道了
怎么吧下面的 2017-01-02": {
、"16777216": {
这2个key和字段id,username一起存入mysql
{
"state": "ok",
"errmsg": "",
"data": {
"2017-01-02": {
"16777216": {
"id": 1,
"username": '李元霸'
}
},
"2017-01-06": {
"16777456": {
"id": 2,
"username": '陈坤'
}
},
}
}
字典存入mysql
我使用过
学习ing2017-06-22 11:53:32
用循环将你需要的数据取出来然后插入到数据库就行了
下面的代码只能处理最简单的情况
#*--encoding: utf8--*
import json
string = '''{
"state": "ok",
"errmsg": "",
"data": {
"2017-01-02": {
"16777216": {
"id": 1,
"username": "李元霸"
}
},
"2017-01-06": {
"16777456": {
"id": 2,
"username": "陈坤"
}
}
}
}'''
ret = json.loads(string)
data = ret['data']
for date in data.keys():
arr = []
arr.append(date)
info = data[date]
arr.append(info.keys()[0])
arr.append(info.values()[0]['id'])
arr.append(info.values()[0]['username'])
print(arr)
此外,你给的json
貌似不怎么正确。。
run code