重音、字符串和 json 的奇怪行为

问题描述 投票:0回答:1

我有带有重音符号的 JSON 数据,并得到了一些意想不到的结果:有时字符会被替换为 �,因为编码错误,但并非每次都如此。

这是问题的重现以及我试图理解逻辑的一些场景

我使用的是Python 3.11.0。 我的所有文件均使用 UTF-8 编码。

这是我为尝试理解逻辑/错误所做的测试。

问题:

# Content of file1.json:
# {"a": "à"}
# Hex dump: 7B 22 61 22 3A 20 22 C3 A0 22 7D

with open("file1.json", "r") as file:
    text = file.read()

print(text) # {"a": "à"}
print(json.loads(text)) # {'a': '�\xa0'}

但这有效

# Content of file2.json:
# "à"
# Hex dump: 22 C3 A0 22

with open("file2.json", "r") as file:
    text = file.read()

print(text) # "à"
print(json.loads(text)) # à

我还尝试使用 UTF-8 打开(我相信这是默认设置?) 这行不通。

with open("file2.json", "r", encoding="utf-8") as file:
    text = file.read()

print(text) # "�"
print(json.loads(text)) # �

然后我尝试只使用字符串,这让我更加困惑

text = '"à"'
print(text) # "�"
print(json.loads(text)) # �
text = '{"a": "à"}'
print(text) # {"a": "�"}
print(json.loads(text)) # {'a': '�'}
json python-3.x character-encoding
1个回答
0
投票

好吧,我找到问题所在了:vs code 输出没有使用 utf-8

我不知道为什么终端输出时没有输出,但我切换到了终端。

现在,结果正如我所料:
注意需要编码参数

with open("file2.json", "r", encoding="utf-8") as file:
    text = file.read()

print(text) # "{"a": "à"}"
print(json.loads(text)) # {'a': 'à'}
© www.soinside.com 2019 - 2024. All rights reserved.