Serialize datetime-like values in _orjson_default (fixes #458)#461
Open
gaoflow wants to merge 1 commit into
Open
Serialize datetime-like values in _orjson_default (fixes #458)#461gaoflow wants to merge 1 commit into
gaoflow wants to merge 1 commit into
Conversation
A figure containing a pandas Timestamp (e.g. a marker x-position) raised `TypeError: Type is not JSON serializable: Timestamp` from write_image / calc_fig. The orjson fallback `_orjson_default` only handled `Decimal` and objects exposing `.tolist()` (NumPy); a Timestamp has neither, so it fell through to `raise TypeError`. Serialize datetime-like objects (anything with `.isoformat()`, e.g. pandas `Timestamp`, `datetime`, `date`) to ISO strings, matching how Plotly's own JSON encoder handles them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Exporting a figure that contains a datetime-like value — e.g. a
pandasTimestampused as a marker position — raises:(reported in #458, a regression in 1.3.0). The orjson fallback
_orjson_defaultonly handlesDecimaland objects exposing.tolist()(NumPy). ATimestamphas neither, so it falls through toraise TypeError.Fix
Serialize datetime-like objects — anything with
.isoformat()(pandasTimestamp,datetime,date) — to ISO strings, which is how Plotly's own JSON encoder represents them. The check is placed before the.tolist()branch sonumpy.datetime64(which has.tolist()but no.isoformat()) is unaffected.Tests
Added a unit test for
_orjson_defaultcovering aTimestamp, adate, an end-to-endorjson.dumpsof a spec carrying aTimestamp, and the existingDecimal/NumPy fallbacks. It fails onmasterwith the originalTypeErrorand passes with the fix.