Python之json的dump和dumps方法

一,dumps

将字典转换为字符串

info_dcit = {'foo1':'a', 'foo2':'b', 'foo3':'c', }
data_dumps = json.dumps(info_dcit, indent=4)
print(data_dumps)
# data_dumps:  
'''
data_dumps:  {
  "foo1": "a",
  "foo2": "b",
  "foo3": "c" 
}
'''

二,dump

将字典保存为json文件

with open('foo_json.json', 'w', encoding='utf-8') as f:
	data_dump = json.dump(info_dcit, f, indent=2)

加载json文件为字典

with open(jsonfile, 'r', encoding='utf-8') as f:
	jsfile = json.load(f)
	print('jsfile: ', jsfile)
# 
# jsfile:  {'foo1': 'a', 'foo2': 'b', 'foo3': 'c'}

你可能感兴趣的:(python)