import json
def json_serialize(name, ftype, path):
prof_info = []
prof_info.append({
'profile_name': name,
'filter_type': ftype
})
with open(path, "w") as f:
json.dumps({'profile_info': prof_info}, f)
json_serialize(profile_name, filter_type, "/home/file.json")
上面的代码不会将数据转储到“file.json”文件中。
当我写
print
之前 json.dumps()
,然后将数据打印在屏幕上。但它不会转储到文件中。
该文件被创建,但在打开它(使用记事本)时,什么也没有。
为什么?
如何纠正?
最佳答案
不是这样json.dumps()
作品。 json.dumps()
返回一个字符串,然后您必须使用 f.write()
将其写入文件.像这样:
with open(path, 'w') as f:
json_str = json.dumps({'profile_info': prof_info})
f.write(json_str)
或者,只需使用
json.dump()
,它的存在正是为了将 JSON 数据转储到文件描述符中。with open(path, 'w') as f:
json.dump({'profile_info': prof_info}, f)
关于json.dumps() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21453117/