如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
如何将存储在字典数据中的JSON数据写入文件?
f = open('data.json', 'wb')
f.write(data)
这会导致错误:
TypeError:必须是字符串或缓冲区,而不是dict
当前回答
使用JSON将数据写入文件,使用JSON.dump()或JSON.dumps()。像这样写以将数据存储在文件中。
import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
json.dump(data, txtfile)
列表中的这个示例存储到文件中。
其他回答
对于那些试图转储希腊语或其他“外来”语言(如我),但同时也遇到诸如和平符号(\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,请使用“漂亮的打印”:
import json
outfile = open('data.json')
json.dump(data, outfile, indent=4)
此外,如果您需要调试格式不正确的JSON,并希望得到有用的错误消息,请使用importsimplejson库,而不是importjson(函数应该相同)
如果您试图使用json格式将panda数据帧写入文件,我建议您这样做
destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()
我会对前面提到的答案稍作修改,即编写一个经过修饰的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)
要获得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文件中获得一个很好的缩进排序结构,代价是文件大小稍大。