如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
json.dump(data, open('data.txt', 'wb'))
其他回答
json.dump(data, open('data.txt', 'wb'))
前面的所有答案都是正确的。这里有一个非常简单的例子:
#! /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()
我没有足够的声誉来添加评论,所以我只在这里写下我对这个烦人的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中运行良好。
这只是对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数据可以按如下方式写入文件
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)