Skip to content

Commit

Permalink
fix: mimetype encoding for tables (#1658)
Browse files Browse the repository at this point in the history
* fix: mimetype encoding for tables

* add test
  • Loading branch information
mscolnick committed Jun 20, 2024
1 parent ff65472 commit 7a5cf73
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 4 additions & 3 deletions marimo/_plugins/core/json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ class WebComponentEncoder(JSONEncoder):

def default(self, o: Any) -> Any:
obj = o
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)

# Handle numpy objects
if DependencyManager.has_numpy():
import numpy as np
Expand Down Expand Up @@ -70,6 +67,10 @@ def default(self, o: Any) -> Any:
(mimetype, data) = obj._mime_()
return {"mimetype": mimetype, "data": data}

# Must come after MIME objects
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)

# Handle bytes objects
if isinstance(obj, bytes):
return obj.decode("utf-8")
Expand Down
14 changes: 14 additions & 0 deletions tests/_plugins/core/test_json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import json
from dataclasses import dataclass

import pytest

Expand Down Expand Up @@ -85,6 +86,7 @@ def test_pandas_encoding() -> None:
assert encoded_other == '["a", "b", "c"]'


@dataclass
class MockMIMEObject:
def _mime_(self) -> tuple[str, str]:
return "text/plain", "data"
Expand All @@ -96,6 +98,18 @@ def test_mime_encoding() -> None:
assert encoded == '{"mimetype": "text/plain", "data": "data"}'


@dataclass
class MockDataclass:
a: int
b: str


def test_dataclass_encoding() -> None:
dataclass_obj = MockDataclass(1, "hello")
encoded = json.dumps(dataclass_obj, cls=WebComponentEncoder)
assert encoded == '{"a": 1, "b": "hello"}'


def test_bytes_encoding() -> None:
bytes_obj = b"hello"
encoded = json.dumps(bytes_obj, cls=WebComponentEncoder)
Expand Down

0 comments on commit 7a5cf73

Please sign in to comment.