python / python/cpython

Handling of surrogates on JSON encoding

Aperta
#93,508 0 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

docs
Lingua principale
Python
Stelle
77.2k
Fork
36k
Merge medio
1g 9h
PR unite (30g)
558

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia dalla sezione «Character encodings» della documentazione JSON, collegata nell'issue. Esamina il comportamento illustrato per i caratteri non-BMP, le coppie di surrogati e i surrogati isolati, quindi documenta la limitazione del round-trip e la sua relazione con ensure_ascii=True. Il lavoro è completato quando la sezione spiega chiaramente quando json.loads(json.dumps(s)) può non essere uguale a s.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
50/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.