怎么把一个dict类型的变量存为json格式的文件到本地?
2个回答
使用dumps将dict转化成json格式写入到json文件中
import json
def dict_to_json():
dict = {}
dict['name'] = '123'
dict['age'] = 10
dict['sex'] = 'male'
#转换成json
j = json.dumps(dict)
#写到json文件
fileObject = open('jsonFile.json', 'w')
fileObject.write(j)
fileObject.close()
if __name__ == '__main__':
dict_to_json()
谢谢
-
猴老大
2018-12-19 13:20
import json
my_dict = {'year': '2018', 'day': '12-04'}
with open('my_dict.json', 'w') as outfile:
json.dump(my_dict, outfile)
谢谢
-
猴老大
2018-12-19 13:20