当前位置: 首页 > 后端技术 > Python

python处理json

时间:2023-03-26 14:15:05 Python

1、dumps:将python中的字典转为字符串importjsontest_dict={'bigberg':[7600,{1:[['iPhone',6300],['Bike',800],['shirt',300]]}]}print(test_dict)print(type(test_dict))#dumps将数据转换成字符串json_str=json.dumps(test_dict)print(json_str)print(type(json_str))2,加载:将字符串转换为字典new_dict=json.loads(json_str)print(new_dict)print(type(new_dict))3、dump:用open("../config/record.json","w")将数据写入json文件asf:json.dump(new_dict,f)print("文件加载完成...")4.load:打开文件,将字符串转换为数据类型open("../config/record.json",'r')asload_f:load_dict=json.load(load_f)print(load_dict)load_dict['smallberg']=[8200,{1:[['Python',81],['shirt',300]]}]print(load_dict)withopen("../config/record.json","w")asdump_f:json.dump(load_dict,dump_f)5.遍历keyvaluetest_json={"a":1,"b":2,"c":3}forkey,valueintest_json.items():printkey,价值