db = pymysql.connect(host='localhost',user='root',passwd='saltneko',db='test3') #连接数据库 cursor = db.cursor() filename='/Users/salt/PycharmProjects/Study/test1.json' with open(filename, 'rb') as f: Data = json.load(f) s = Data['options']['checks'] #直接取字典的键值 i = 1 for a in s: sql='insert into web_loophole_type (Id,Web_loophole_type_description_en) values(' + str( i) + ",'" + a + "'" + ');' cursor.execute(sql) db.commit() i = i + 1
db = pymysql.connect(host='localhost',user='root',passwd='saltneko',db='test3') cursor = db.cursor() filename='/Users/salt/PycharmProjects/Study/test1.json' with open(filename, 'rb') as f: Data = json.load(f) s1 = Data['sitemap'] s2 = Data['plugins']['healthmap']['results']['map'] i = 1 #map作为一个列表,通过遍历其中取出的key为字典 for key1 in s1.keys(): for i in s2: try: key1 = (i['without_issues']) except: continue #因为存在with_issues和without_issues俩种键,加入异常处理 sql='insert into sitemap(Id,Sitemap,Healthymap) values(' + str(i) + ",'" + key1 + "'" + ",'"+key2+"'"+');' cursor.execute(sql) db.commit() i=i+1
or
1 2 3 4 5 6 7 8 9 10
with open(filename, 'rb') as f: Data = json.load(f) s1 = Data['sitemap'] s2 = Data['plugins']['healthmap']['results']['map'] for key1 in s1.keys(): for key2 in s2: if key2.get('without_issues'): key2=key2.get('without_issues') print(key2) #get到的值数量等于键值,可能存在空值
#通过遍历数组对其中包含的字典取出键值
``` import pymysql import json
db = pymysql.connect(host=’localhost’,user=’root’,passwd=’saltneko’,db=’test3’) cursor = db.cursor() filename=’/Users/salt/PycharmProjects/Study/test1.json’ with open(filename, ‘rb’) as f: Data = json.load(f) s1 = Data[‘issues’] #issues作为一个列表,通过遍历其中取出的i为字典 for i in s1: print(i[‘vector’][‘url’])#继续解析字典
1 2 3 4 5 6 7 8 9 10
### #字典包含数组 ```favourite_places={ 'a':['1','2','3'], 'b':['1','2','3'], 'c':['1','2','3'], } for key,value in favourite_places.items(): print(key+"'s favourite places are :" ) for key2 in value: print(key2)