如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
前面的所有答案都是正确的。这里有一个非常简单的例子:
#! /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()
其他回答
在将字典作为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)
公认的答案是好的。然而,我使用它时遇到了“is not json serializable”错误。
这是我修复它的方法以open(“filename.json”,'w')作为输出:
output.write(str(响应))
虽然这不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果您希望快速而肮脏,这是很好的。
对于那些试图转储希腊语或其他“外来”语言(如我),但同时也遇到诸如和平符号(\u262E)等奇怪字符或其他通常包含在json格式数据(如Twitter)中的字符的问题(unicode错误)的人,解决方案可能如下(sort_keys显然是可选的):
import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))
如果您试图使用json格式将panda数据帧写入文件,我建议您这样做
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
使用JSON将数据写入文件,使用JSON.dump()或JSON.dumps()。像这样写以将数据存储在文件中。
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
列表中的这个示例存储到文件中。