ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
```python import json # json字符串转换python数据类型 json.loads(json_str) # 读取json文件 with open(json_file, 'b') as f: data = json.load(f) # python数据类型转json字符串 json.dumps(data_object) # python数据类型写入json文件 with open(json_file, 'w', encoding='utf-8') as f: json.dump(data_object, f) # 或者f.write(json.dumps(data_object)) ``` <br/> 举例: ```python """ @Date 2021/4/24 """ import requests import os from urllib.request import urlretrieve import json def parse_net_json(): """ 1. 读取从网上爬取的json数据 2. 下载图片 """ hero_url = 'http://gamehelper.gm825.com/wzry/hero/list' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36' } hero_images = 'E:/hero_images' if not os.path.exists(hero_images): os.mkdir(hero_images) response = requests.get(hero_url, headers=headers) json_data = response.json() for item in json_data['list']: hero_name = item['name'] hero_image = item['cover'] file_path = hero_images + '/' + hero_name + '.png' # 下载图片 urlretrieve(hero_image, file_path) def write_data_to_json(): """ json对象写入json文件中 """ json_object = [ {'name': '张三', 'age': 24, 'gender': '男'}, {'name': '李四', 'age': 26, 'gender': '男'} ] # json.dumps(object)可以将python对象转换为字符串 json_str = json.dumps(json_object) # [{"name": "\u5f20\u4e09", "age": 24, "gender": "\u7537"}, {"name": "\u674e\u56db", "age": 26, "gender": "\u7537"}] print(json_str) # student.json文件中写入数据格式为 # :[{"name": "\u5f20\u4e09", "age": 24, "gender": "\u7537"}, {"name": "\u674e\u56db", "age": 26, "gender": "\u7537"}] with open('E:/json/student.json', 'w', encoding='utf-8') as f: json.dump(json_object, f) # 或者使用f.write(json_str) def read_data_from_json(): """ 读取json文件 """ with open('E:/json/student.json', 'rb') as f: content = json.load(f) # <class 'list'> print(type(content)) # [{'name': '张三', 'age': 24, 'gender': '男'}, {'name': '李四', 'age': 26, 'gender': '男'}] print(content) if __name__ == "__main__": # parse_net_json() # write_data_to_json() read_data_from_json() ```