新建一个python文件命名为py3_json.py,在这个文件中进行操作代码编写:
import json#定义一个json字符串people_str = '''{ \"大众people\公众:[ { \"大众name\"大众:\"大众yale\"大众, \"大众age\"大众 : 25, \"大众email\"大众 :\公众yale@email.com\"大众 }, { \"大众name\公众:\"大众McBag\"大众, \"大众age\"大众 : 30, \公众email\公众 :null } ]}'''#利用json.loads()加载字符串data = json.loads(people_str)print(data)#返回的是一个python字典#{'people': [{'name': 'yale', 'age': 25, 'email': 'yale@email.com'}#, {'name': 'McBag', 'age': 30, 'email': None}]}print(type(data['people']))#返回<class 'list'>#我们循环读取数据for people in data['people']: print(people) #print(people['name'])#{'name': 'yale', 'age': 25, 'email': 'yale@email.com'}#{'name': 'McBag', 'age': 30, 'email': None}#删除email信息for people in data['people']: del people['email']#利用json.dumps()#将Python工具编码成JSON字符串#indent缩进显示#sort_keys按照key排序new_string = json.dumps(data,indent=1,sort_keys=True)print(new_string)#打印结果:'''{ \"大众people\公众: [ { \"大众name\"大众: \"大众yale\"大众, \"大众age\"大众: 25 }, { \"大众name\"大众: \"大众McBag\"大众, \"大众age\"大众: 30 } ]}'''#加载json文件with open('people.json','r') as f: data = json.load(f)#打印数据for person in data['people']: print(person['name'],person['age'],person['email']) #写入json文件for person in data['people']: del person['email']with open('new_data.json','w') as wf: new_json = json.dumps(data,indent=2) wf.write(new_json)#读取新浪新闻的jsonimport refrom urllib.request import urlopen#要求一个新浪新闻地址with urlopen('''http://top.news.sina.com.cn/ws/GetTopDataList.php?top_type=day&top_cat=qbpdpl&top_time=20190531&top_show_num=100&top_order=DESC&js_var=comment_all_data''') as response: source = response.read() source = source.decode()#正则匹配出json字符串部分 try: pattern = re.compile(r'\{\公众conf\"大众.\}\]\}') matches = pattern.findall(source) data = json.loads(matches[0]) for item in data['data']: print(item['id'],item['title'])except Exception as e: print('出错了',e)#部分运行效果:#5208 有埃神的恒大曾代表中国 那有埃神的国足为何弗成#5215 浅肤色直长发 30位印度小姐候选佳丽照引网友关注#5222 《复联》拍摄地通过最严反堕胎法 迪士尼或将撤出#5229 《破冰行动》导演为逻辑Bug道歉 回应感情戏多余
运行结果:
{'people': [{'name': 'yale', 'age': 25, 'email': 'yale@email.com'}, {'name': 'McBag', 'age': 30, 'email': None}]}<class 'list'>{'name': 'yale', 'age': 25, 'email': 'yale@email.com'}{'name': 'McBag', 'age': 30, 'email': None}{ \"大众people\"大众: [ { \公众age\"大众: 25, \"大众name\"大众: \公众yale\"大众 }, { \"大众age\公众: 30, \"大众name\"大众: \"大众McBag\公众 } ]}yale 25 yale@email.comMcBag 30 NoneTestUser 30 testuser@163.com5208 《破冰行动》导演为逻辑Bug道歉 回应感情戏多余5215 库里34+5双卡55分 猛龙击退勇士总决赛1-0领先......
本日初学python的json模块学习就到这里!

关注公号yale记
下面的是我的公众年夜众号二维码图片,欢迎关注。