I’m working on converting portions of XHTML to JSON objects. I finally got everything in JSON form, but some UTF-8 character codes are being printed. Example:
JavaScript
x
7
1
{
2
"p": {
3
"@class": "para-p",
4
"#text": "Iu2019m not on Earth."
5
}
6
}
7
This should be:
JavaScript
1
7
1
{
2
"p": {
3
"@class": "para-p",
4
"#text": "I'm not on Earth."
5
}
6
}
7
This is just one example of UTF-8 codes coming through. How can I got through the string and replace every instance of a UTF-8 code with the character it represents?
Advertisement
Answer
u2019
is not a UTF-8 character, but a Unicode escape code. It’s valid JSON and when read back via json.load
will become ’
(RIGHT SINGLE QUOTATION MARK).
If you want to write the actual character, use ensure_ascii=False
to prevent escape codes from being written for non-ASCII characters:
JavaScript
1
3
1
with open('output.json','w',encoding='utf8') as f:
2
json.dump(data, f, ensure_ascii=False, indent=2)
3