python使用json.dump()的中文编码问题

当json中有中文字符串时:

  • open时加上encoding=‘utf-8',
  • dump时加上ensure_ascii=False,(这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False

 

dump示例(爬取页面编码为gbk字符集):

  • 打开json文件时没有指定编码,报错
...
with open("kuaiji7.json",mode='w') as f :
    json.dump(dict_users,f,ensure_ascii=False)
...

报错:

 File "D:/bd/kuaiji/k.py", line 76, in 
    json.dump(dict_users,f,ensure_ascii=False)
 File "C:\Users\t\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 180, in dump
    fp.write(chunk)
UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 1: illegal multibyte sequenc
  • 存储到json文件时不禁用默认的ascii,中文显示为ascii字符
...
with open("kj9.json",mode='w',encoding="utf-8") as f :
    json.dump(dict_users,f) #,ensure_ascii=False
...

json文件写入ascii字符:

{
  "users": 
    [
      {
         ...
        "email_status": "\u90ae\u7bb1\u72b6\u6001\u672a\u9a8c\u8bc1"
      }
    ]
  }
  • 禁用默认的ascii,输出中文
...
with open("kj10.json",mode='w',encoding="utf-8") as f :
    json.dump(dict_users,f,ensure_ascii=False)
...
{
  "users": 
    [
      {
         ...
        "email_status": "邮箱状态未验证"
      }
    ]
  }

你可能感兴趣的:(python,python3,json,dump)