dumps()与dump()区别

dumps是将dict转化成json字符串格式,loads是将json字符串转化成dict格式。

dump和load也是类似的功能,只是与文件操作结合起来了。


dump(写入内容,文件对象) 和load(文件对象)

代码实现:

def write_file():

like_num = input('请输入您喜欢的数字:')

with open('C:\\Users\\Administrator\\Desktop\\data.json','w') as fw:

json.dump(like_num,fw) # 将内容写入文件

with open('C:\\Users\\Administrator\\Desktop\\data.json','r') as fr:

data = json.load(fr) # 读取文件内容

return data

data = write_file()

print("I know your favorite number! It's {}.".format(data))


dumps() 和loads()

data = {'key1':1,'key2':2}

print(json.dumps(data)) #{"key1": 1, "key2": 2}

print(json.loads(json.dumps(data))) #{'key1': 1, 'key2': 2}