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:  <class 'str'>
'''
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)
# <class 'dict'>
# jsfile:  {'foo1': 'a', 'foo2': 'b', 'foo3': 'c'}

猜你喜欢

转载自blog.csdn.net/m0_47026232/article/details/133527553