Handling of surrogates on JSON encoding
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 77.2k
- Forks
- 36k
- Ø Merge
- 1 T. 9 Std.
- Gemergte PRs (30 T.)
- 558
Beschreibung
When json.dumps is called with ensure_ascii = True (the default), the output does not distinguish between Unicode characters outside of the BMP and their corresponding surrogate characters. This means that json.loads(json.dumps(s)) is not guaranteed to return s:
>>> json.loads(json.dumps('𝄞')) == '𝄞'
True
>>> json.loads(json.dumps('\ud834\udd1e')) == '\ud834\udd1e'
False
The only way to get surrogate characters back is to have them in the JSON string as actual characters, not escaped:
>>> json.loads( '"\ud83d\udca9"') # Actual surrogate characters
'\ud83d\udca9'
>>> json.loads(r'"\ud83d\udca9"') # Escaped surrogates
'💩'
Python does handle the case of lone surrogates reasonably (although RFC 8259 basically declares this undefined behaviour), so the round-trip does work in some cases:
>>> json.loads(json.dumps('\ud83d'))
'\ud83d'
It would seem reasonable to expect that json.loads(json.dumps(s)) == s would hold for any string. This isn't really a bug but rather a limitation of pure-ASCII encoding. However, I think it does deserve a mention in the documentation. Possibly at the end of the Character encodings section? I'm not quite sure.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie mit dem im Issue verlinkten Abschnitt „Character encodings“ der JSON-Dokumentation. Überprüfen Sie das demonstrierte Verhalten für Zeichen außerhalb der BMP, Surrogatpaare und einzelne Surrogate, und dokumentieren Sie die Einschränkung beim Round-Trip sowie ihren Zusammenhang mit ensure_ascii=True. Als erledigt gilt die Aufgabe, wenn der Abschnitt klar erklärt, wann json.loads(json.dumps(s)) möglicherweise nicht gleich s ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 50/100