Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions plotly/io/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,9 @@ def write_json(fig, file, validate=True, pretty=False, remove_uids=True, engine=
else:
# We previously succeeded in interpreting `file` as a pathlib object.
# Now we can use `write_bytes()`.
path.write_text(json_str)
# Explicit UTF-8: Windows default encodings (e.g. cp1252) raise
# UnicodeEncodeError for non-ASCII figure text (#5665).
path.write_text(json_str, encoding="utf-8")


def from_json_plotly(value, engine=None):
Expand Down Expand Up @@ -464,7 +466,9 @@ def read_json(file, output_type="Figure", skip_invalid=False, engine=None):
# Read file contents into JSON string
# -----------------------------------
if path is not None:
json_str = path.read_text()
# Explicit UTF-8 so files written by write_json decode correctly on
# Windows (default locale encoding is often not UTF-8) (#5665).
json_str = path.read_text(encoding="utf-8")
else:
json_str = file.read()

Expand Down
14 changes: 14 additions & 0 deletions tests/test_io/test_to_from_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,17 @@ def test_to_dict_empty_np_array_int64():
)
# to_dict() should not raise an exception
fig.to_dict()


def test_write_read_json_utf8_non_ascii(tmp_path):
"""write_json/read_json must use UTF-8 so Windows cp1252 locales work (#5665)."""
fig = go.Figure(layout_title_text="μ 中文")
path = tmp_path / "fig_utf8.json"
pio.write_json(fig, path)
# File bytes must be valid UTF-8 containing the title characters
raw = path.read_bytes()
raw.decode("utf-8")
assert "μ".encode("utf-8") in raw or "\\u03bc".encode("ascii") in raw
loaded = pio.read_json(path)
title = loaded.layout.title.text
assert "μ" in title and "中文" in title