如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
JSON数据可以按如下方式写入文件
hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]
写入文件:
with open('text1.json', 'w') as f:
json.dump(hist1, f)
其他回答
前面的所有答案都是正确的。这里有一个非常简单的例子:
#! /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格式将panda数据帧写入文件,我建议您这样做
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
要使用缩进编写JSON,请使用“漂亮的打印”:
import json
outfile = open('data.json')
json.dump(data, outfile, indent=4)
此外,如果您需要调试格式不正确的JSON,并希望得到有用的错误消息,请使用importsimplejson库,而不是importjson(函数应该相同)
使用Python 2+3读写JSON文件;使用unicode
# -*- coding: utf-8 -*-
import json
# Make it work for Python 2+3 and with Unicode
import io
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],
'a string': 'bla',
'another dict': {'foo': 'bar',
'key': 'value',
'the answer': 42}}
# Write JSON file
with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
# Read JSON file
with open('data.json') as data_file:
data_loaded = json.load(data_file)
print(data == data_loaded)
json.dump参数说明:
indent:使用4个空格来缩进每个条目,例如,当一个新的dict开始时(否则所有的都将在一行中),sortkeys:对字典的关键字进行排序。如果您想将json文件与diff工具进行比较/将其置于版本控制之下,这非常有用。分隔符:防止Python添加尾随空格
带一个包装
看看我的实用程序包mpu,找到一个超级简单、易于记忆的:
import mpu.io
data = mpu.io.read('example.json')
mpu.io.write('example.json', data)
已创建JSON文件
{
"a list":[
1,
42,
3.141,
1337,
"help",
"€"
],
"a string":"bla",
"another dict":{
"foo":"bar",
"key":"value",
"the answer":42
}
}
常用文件结尾
.json文件
选择
CSV:超简单格式(读写)JSON:适合编写人类可读数据;非常常用(读写)YAML:YAML是JSON的超集,但更易于阅读(读写,JSON和YAML的比较)pickle:Python序列化格式(读写)MessagePack(Python包):更紧凑的表示(读写)HDF5(Python包):适合矩阵(读写)XML:也存在*叹息*(读写)
对于您的应用程序,以下内容可能很重要:
其他编程语言的支持读/写性能紧凑性(文件大小)
另请参阅:数据序列化格式的比较
如果您正在寻找创建配置文件的方法,您可能需要阅读我的Python配置文件短文
使用JSON将数据写入文件,使用JSON.dump()或JSON.dumps()。像这样写以将数据存储在文件中。
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
列表中的这个示例存储到文件中。