如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
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文档。
要获得utf8编码文件,而不是Python 2公认答案中的ascii编码文件,请使用:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
Python 3中的代码更简单:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
在Windows上,仍然需要使用encoding='utf-8'参数打开。
要避免在内存中存储数据的编码副本(转储的结果),并在Python 2和3中输出utf8编码字节字符串,请使用:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
codecs.getwriter调用在Python 3中是冗余的,但在Python 2中是必需的
可读性和尺寸:
ensure_ascii=False的使用提供了更好的可读性和更小的大小:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
通过在dump或dumps的参数中添加标志indent=4,sort_keys=True(如dinos66所建议的),进一步提高可读性。通过这种方式,您将在json文件中获得一个很好的缩进排序结构,代价是文件大小稍大。
我会对前面提到的答案稍作修改,即编写一个经过修饰的JSON文件,人眼可以更好地阅读。为此,将sort_keys传递为True,并用4个空格字符缩进,就可以开始了。还要注意确保ascii代码不会写入JSON文件:
with open('data.txt', 'w') as out_file:
json.dump(json_data, out_file, sort_keys = True, indent = 4,
ensure_ascii = False)
对于那些试图转储希腊语或其他“外来”语言(如我),但同时也遇到诸如和平符号(\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将数据写入文件,使用JSON.dump()或JSON.dumps()。像这样写以将数据存储在文件中。
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
列表中的这个示例存储到文件中。
我没有足够的声誉来添加评论,所以我只在这里写下我对这个烦人的TypeError的一些发现:
基本上,我认为这只是Python 2中json.dump()函数中的一个bug——它无法转储包含非ASCII字符的Python(字典/列表)数据,即使您使用encoding='utf-8'参数打开文件。(即无论你做什么)。但是,json.dumps()在Python 2和3上都有效。
为了说明这一点,接下来是phihag的回答:如果数据包含非ASCII字符,他的回答中的代码在Python 2中中断,出现异常TypeError:必须是unicode,而不是str。(Python 2.7.6,Debian):
import json
data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
然而,它在Python 3中运行良好。
使用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格式将panda数据帧写入文件,我建议您这样做
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
前面的所有答案都是正确的。这里有一个非常简单的例子:
#! /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()
公认的答案是好的。然而,我使用它时遇到了“is not json serializable”错误。
这是我修复它的方法以open(“filename.json”,'w')作为输出:
output.write(str(响应))
虽然这不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果您希望快速而肮脏,这是很好的。
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)
要使用缩进编写JSON,请使用“漂亮的打印”:
import json
outfile = open('data.json')
json.dump(data, outfile, indent=4)
此外,如果您需要调试格式不正确的JSON,并希望得到有用的错误消息,请使用importsimplejson库,而不是importjson(函数应该相同)
这只是对json.dumps用法的一个额外提示(这不是问题的答案,而是那些必须转储numpy数据类型的人的一个技巧):
如果字典中有NumPy数据类型,json.dumps()需要一个额外的参数,信用转到TypeError:'ndarray'类型的对象不可json序列化,它还将修复TypeError:int64类型的对象不能json序列化等错误:
class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for np types """
def default(self, obj):
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)):
return int(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32,
np.float64)):
return float(obj)
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
然后运行:
import json
#print(json.dumps(my_data[:2], indent=4, cls=NumpyEncoder)))
with open(my_dir+'/my_filename.json', 'w') as f:
json.dumps(my_data, indent=4, cls=NumpyEncoder)))
在np.array()的情况下,您可能还希望返回字符串而不是列表,因为数组被打印为分布在行上的列表,如果您有大或多个数组,则会放大输出。需要注意的是:稍后从转储的字典中访问项以将其恢复为原始数组会更加困难。然而,如果您不介意只使用一个数组字符串,这会使字典更可读。然后交换:
elif isinstance(obj, (np.ndarray,)):
return obj.tolist()
具有:
elif isinstance(obj, (np.ndarray,)):
return str(obj)
或者只是:
else:
return str(obj)
在将字典作为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)
对于喜欢oneliner的人(因此,with语句不是一个选项),一个比留下悬空打开的文件描述符更干净的方法是使用pathlib中的write_text并执行以下操作:
pathlib.Path("data.txt").write_text(json.dumps(data))
在某些情况下,这在不允许语句的上下文中很有用,例如:
[pathlib.Path(f"data_{x}.json").write_text(json.dumps(x)) for x in [1, 2, 3]]
我并不是说它应该优先于使用(而且可能会慢一些),只是另一种选择。