Handling of surrogates on JSON encoding

Đang mở
#93,508 0 bình luận 2 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức phù hợp với người mới
50/100
Loại issue
Tài liệu
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
documentation

Hướng nghiên cứu

Bắt đầu từ phần “Character encodings” trong tài liệu JSON được liên kết trong issue. Xem lại hành vi được minh họa đối với các ký tự ngoài BMP, các cặp surrogate và các surrogate đơn lẻ, sau đó ghi lại giới hạn của round-trip và mối liên hệ của nó với ensure_ascii=True. Công việc được xem là hoàn tất khi phần này giải thích rõ khi nào json.loads(json.dumps(s)) có thể không bằng s.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

docs

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.

Ngôn ngữ chính
Python
Star
77.2k
Fork
36k
Merge trung bình
1 ngày 9 giờ
Pull request đã merge (30 ngày)
558

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của python/cpython

Tất cả issue của python/cpython

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.