json.dump时需要类似字节的对象,而不是“str”错误

2024-09-21 03:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将dict转储到JSON文件中。下面附带的代码在Python2中工作,但是当我尝试在Python3上运行它时,我遇到了上面提到的错误

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”来写,但后来我得到了一个答案 'Int64类型的对象不可JSON序列化'


Tags: 文件代码importjsonfalsedata错误item
1条回答
网友
1楼 · 发布于 2024-09-21 03:23:35

在Python3中,二进制输出文件必须接收字节字符串,而不是普通的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)

相关问题 更多 >

    热门问题