如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
公认的答案是好的。然而,我使用它时遇到了“is not json serializable”错误。
这是我修复它的方法以open(“filename.json”,'w')作为输出:
output.write(str(响应))
虽然这不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果您希望快速而肮脏,这是很好的。
其他回答
要使用缩进编写JSON,请使用“漂亮的打印”:
import json
outfile = open('data.json')
json.dump(data, outfile, indent=4)
此外,如果您需要调试格式不正确的JSON,并希望得到有用的错误消息,请使用importsimplejson库,而不是importjson(函数应该相同)
公认的答案是好的。然而,我使用它时遇到了“is not json serializable”错误。
这是我修复它的方法以open(“filename.json”,'w')作为输出:
output.write(str(响应))
虽然这不是一个很好的修复方法,因为它创建的json文件不会有双引号,但是如果您希望快速而肮脏,这是很好的。
这只是对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)
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文档。
我会对前面提到的答案稍作修改,即编写一个经过修饰的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)