如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
在将字典作为json写入文件之前,必须使用json库将该字典转换为json字符串。
import json
data = {
"field1":{
"a": 10,
"b": 20,
},
"field2":{
"c": 30,
"d": 40,
},
}
json_data = json.dumps(json_data)
此外,您还可以向json数据添加缩进以使其看起来更漂亮。
json_data = json.dumps(json_data, indent=4)
如果要在转换为json之前对密钥进行排序,
json_data = json.dumps(json_data, sort_keys=True)
您也可以使用这两者的组合。
有关更多功能,请参阅此处的json文档
最后,您可以写入一个json文件
f = open('data.json', 'wb')
f.write(json_data)
其他回答
json.dump(data, open('data.txt', 'wb'))
data是Python字典。在编写之前,需要将其编码为JSON。
使用此选项可获得最大兼容性(Python 2和3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
在现代系统(即Python 3和UTF-8支持)上,您可以使用以下方法编写更好的文件:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
请参阅json文档。
公认的答案是好的。然而,我使用它时遇到了“is not json serializable”错误。
这是我修复它的方法以open(“filename.json”,'w')作为输出:
output.write(str(响应))
虽然这不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果您希望快速而肮脏,这是很好的。
使用JSON将数据写入文件,使用JSON.dump()或JSON.dumps()。像这样写以将数据存储在文件中。
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
列表中的这个示例存储到文件中。
前面的所有答案都是正确的。这里有一个非常简单的例子:
#! /usr/bin/env python
import json
def write_json():
# create a dictionary
student_data = {"students":[]}
#create a list
data_holder = student_data["students"]
# just a counter
counter = 0
#loop through if you have multiple items..
while counter < 3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter += 1
#write the file
file_path='/tmp/student_data.json'
with open(file_path, 'w') as outfile:
print("writing file to: ",file_path)
# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()
print("done")
write_json()