python3处理json文件中含有中文的应用

2020-03-11  本文已影响0人  丶Assassin丨

# -*- coding:utf-8 -*-

import json

json_data = '{"department": "非制作部", "username": "zhaos", "realname": "赵四"}, {"department": "制作一部", "username": "wangcy", "realname": "王春雨"}, {"department": "非制作部", "username": "zhangs", "realname": "张三"}, {"department": "非制作部", "username": "zhaott", "realname": "赵涛涛"}, {"department": "非制作部", "username": "wuc", "realname": "吴成"}'

user_data = json.loads(json.dumps(json_data, ensure_ascii=False, indent=4))

print(user_data)

通过string转成json后,再通过json.dumps转成字符串后,中文得以解析

dumps_str = json.dumps(json_data, ensure_ascii=False, indent=4)

dumps_str

Out[30]: '{\n    "f": "100\\n",\n    "a": " 1",\n    "b": "好好学习"\n}'

如果报错

报错信息为:Non-UTF-8 code starting with '\xe4'

python3默认使用UTF-8格式

开头一般不用加 # -*- coding:utf-8 -*-

但是有的中文中还是会出现无法识别的情况,抛出Non-UTF-8 code starting with '\xe7'  错误,这时候就需要在第一行加上这句。

# -*- coding:utf-8 -*-

上一篇下一篇

猜你喜欢

热点阅读