python json加载设置编码为utf-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46408051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:37:25  来源:igfitidea点击:

python json load set encoding to utf-8

pythonpython-3.x

提问by user2950593

I have this code:

我有这个代码:

keys_file = open("keys.json")
keys = keys_file.read().encode('utf-8')
keys_json = json.loads(keys)
print(keys_json)

There are some none-english characters in keys.json. But as a result I get:

在keys.json 中有一些非英文字符。但结果我得到:

[{'category': 'Р?Р±С?', 'keys': ['Р‘Р?РμР?Р?РμС? Philips',
'Р?С?Р?С?С?РёР?Р°С?Р?Р° Polaris']}, {'category': 'Р?Р‘Р?', 'keys':
['С…Р?Р?Р?Р? РёР?С?Р?РёР? Р°С?Р?Р°Р?С?', 'Р?Р?С?С?Р?Р?Р?Р?РμС?Р?Р°С?
Р?Р°СРёР?Р° Bosch']}]

what do I do?

我该怎么办?

回答by deceze

encodemeans characters to binary. What you want when readinga file is binary to charactersdecode. But really this entire process is way too manual, simply do this:

encode表示字符到二进制读取文件时您想要的是二进制到字符decode。但实际上整个过程太手动了,只需执行以下操作:

with open('keys.json', encoding='utf-8') as fh:
    data = json.load(fh)

print(data)

withhandles the correct opening and closing of the file, the encodingargument to openensures the file is read using the correct encoding, and the loadcall reads directly from the file handle instead of storing a copy of the file contents in memory first.

with处理文件的正确打开和关闭,确保使用正确编码读取文件的encoding参数open,并且load调用直接从文件句柄读取而不是首先将文件内容的副本存储在内存中。

If this still outputs invalid characters, it means your source encoding isn't UTF-8 or your console/terminal doesn't handle UTF-8.

如果这仍然输出无效字符,则意味着您的源编码不是 UTF-8 或您的控制台/终端不处理 UTF-8。