ITPub博客

首页 > IT职业 > IT图书 > python json中文乱码怎么解决

python json中文乱码怎么解决

IT图书 作者:lenghuo 时间:2021-09-11 10:31:08 0 删除 编辑

Python实现的json文件读取及中文乱码显示问题解决方法。分享给大家供大家参考,具体如下:

city.json文件的内容如下:

{
 "cities": [
  {
   "city": "北京",
   "cityid": "101010100"
  },
  {
   "city": "上海",
   "cityid": "101020100"
  }
  ]
}

可见,其中包含了中文。

相关推荐:《Python入门教程》

Python使用json.loads之后打印中文会出现乱码的问题,解决方法如下:

with open('city.json', 'r') as json_file:
  """
  读取该json文件时,先按照gbk的方式对其解码再编码为utf-8的格式
  """
  data = json_file.read().decode(encoding='gbk').encode(encoding='utf-8')
  print type(data)  # type(data) = 'str'
  result = json.loads(data)
  new_result = json.dumps(result,ensure_ascii=False) # 参考网上的方法,***ensure_ascii***设为False
  print new_result
# 输出结果:
# "cities": [{"cityid": "101010100", "city": "北京"}, {"cityid": "101020100", "city": "上海"}]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2989/viewspace-2836171/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: django框架难学么
请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    68
  • 访问量
    806