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()
I can handle this kind of deposit, but I don’t know how to add the key.
How about the following 2017-01-02": {
、"16777216": {
These two keys are stored in mysql
{
"state": "ok",
"errmsg": "",
"data": {
"2017-01-02": {
"16777216": {
"id": 1,
"username": '李元霸'
}
},
"2017-01-06": {
"16777456": {
"id": 2,
"username": '陈坤'
}
},
}
}
Dictionary stored in mysql
I have used it
高洛峰2017-06-22 11:53:32
d = {
"state": "ok",
"errmsg": "",
"data": {
"2017-01-02": {
"16777216": {
"id": 1,
"username": '李元霸'
}
},
"2017-01-06": {
"16777456": {
"id": 2,
"username": '陈坤'
}
},
}
}
for k, v in d['data'].iteritems():
number = v.keys()[0]
print k, number, v[number]['id'], v[number]['username']
学习ing2017-06-22 11:53:32
Just use a loop to take out the data you need and insert it into the database
The following code can only handle the simplest case
#*--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)
Besides, the json
you gave doesn’t seem to be very correct. .
run code