1.json.dump()是通过文件的形式进行处理,举个栗子:
1 import json 2
3 my_dict = dict() 4 with open('labels.txt', 'r', encoding='utf-8') as f: 5 contents = f.readlines() 6 for content in contents: 7 key = content.split(':')[0] 8 label_1 = content.split(':')[1].split(',')[0] 9 label_2 = content.split(':')[1].split(',')[1] 10 value = [label_1, label_2] 11 my_dict[key] = value 12
13 with open('./filename.json', 'w', encoding='utf-8') as f: 14 json.dump(my_dict, f)
label.txt内容如下:
2:'地地意同了H', 'rreree'
4:'3YP65G', 'ybbreb'
2.json.dumps()是将字典转换为json,不通过文件,举个栗子
import json data = { 'name' : 'soap', 'shares' : 90, 'price' : 542.23 } json_str = json.dumps(data)