Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

python json load set encoding to utf-8

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:

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

what do I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

encode means characters to binary. What you want when reading a file is binary to charactersdecode. But really this entire process is way too manual, simply do this:

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

print(data)

with handles the correct opening and closing of the file, the encoding argument to open ensures the file is read using the correct encoding, and the load call reads directly from the file handle instead of storing a copy of the file contents in memory first.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...