需要一个类似字节的对象,而不是 'str' 错误而 json.dump

a bytes-like object is required, not 'str' error while json.dump

我正在尝试将字典转储到 JSON 文件中。下面附带的代码在 python 2 中有效,但是当我在 python 3 上尝试 运行 时出现上述错误。

import json
for terr_item in data:    
    with open( 'influence_data/' + str(terr_item['territory_id']) +'-influence.json','wb') as f:
        json.dump(terr_item,f,ensure_ascii=False,allow_nan=False,indent=4)

编辑:

我也尝试使用 'w' 来写,但后来我得到了 'Object of type Int64 is not JSON serializable'

在 Python 3 中,binary 输出文件必须接收字节字符串而不是正常的 Python3 unicode 字符串。

这里你没有理由使用二进制模式,所以你应该使用:

with open( 'influence_data/' + str(terr_item['territory_id']) +'-influence.json','w') as f:
    json.dump(terr_item,f,ensure_ascii=False,allow_nan=False,indent=4)