代码
import json
# 将json数据对象写入文件
def json_file_write(json_filename):
# json object
jack = {'Name': 'JACK Williams',
'ID': 391568,
'At School': True}
# write json object to file
with open(json_filename, mode='w') as json_file:
json.dump(jack, json_file)
# 从文件读入json数据对象
def json_file_read(json_filename):
# load json object from file
with open(json_filename) as json_file:
json_object = json.load(json_file)
# output the json object
print(json_object)
# 程序入口
if __name__ == '__main__':
# set a json file name
filename_jack = 'jack.txt'
# save json object as a file
json_file_write(filename_jack)
# load json object from a file
json_file_read(filename_jack)
效果(程序输出)
{'Name': 'JACK Williams', 'ID': 391568, 'At School': True}