Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: json & list view in datatables (#4122)

Shahmir Varqha7190b2fa0f47
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index dfe7fe4315..82a8b8976b 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -24,6 +24,11 @@ import { DatePopover } from "./date-popover";
import { Objects } from "@/utils/objects";
import { Maps } from "@/utils/maps";
import { exactDateTime } from "@/utils/dates";
+import { JsonOutput } from "../editor/output/JsonOutput";
+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+import { EmotionCacheProvider } from "../editor/output/EmotionCacheProvider";
+import { PopoverClose } from "@radix-ui/react-popover";
+import { Button } from "../ui/button";
function inferDataType(value: unknown): [type: DataType, displayType: string] {
if (typeof value === "string") {
@@ -273,6 +278,42 @@ export function generateColumns<T>({
);
}
+ if (Array.isArray(value) || typeof value === "object") {
+ const rawStringValue = renderAny(value);
+ return (
+ <div
+ onClick={selectCell}
+ className={getCellStyleClass(
+ justify,
+ wrapped,
+ canSelectCell,
+ isCellSelected,
+ )}
+ >
+ <EmotionCacheProvider container={null}>
+ <Popover>
+ <PopoverTrigger>
+ <span
+ className="cursor-pointer hover:text-link"
+ title={rawStringValue}
+ >
+ {rawStringValue}
+ </span>
+ </PopoverTrigger>
+ <PopoverContent>
+ <PopoverClose className="absolute top-2 right-2">
+ <Button variant="link" size="xs">
+ Close
+ </Button>
+ </PopoverClose>
+ <JsonOutput data={value} format="tree" />
+ </PopoverContent>
+ </Popover>
+ </EmotionCacheProvider>
+ </div>
+ );
+ }
+
return (
<div
onClick={selectCell}
@@ -375,13 +416,14 @@ function getCellStyleClass(
"relative before:absolute before:inset-0 before:bg-[var(--blue-3)] before:rounded before:-z-10 before:mx-[-4px] before:my-[-2px]",
"w-full",
"text-left",
+ "truncate",
justify === "center" && "text-center",
justify === "right" && "text-right",
wrapped && "whitespace-pre-wrap min-w-[200px] break-words",
);
}
-function renderAny(value: unknown): React.ReactNode {
+function renderAny(value: unknown): string {
if (value == null) {
return "";
}
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index c677a0cd24..c54dbe7455 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -801,7 +801,7 @@ const DatasetColumnPreview: React.FC<{
}
const error = preview.error && (
- <div className="text-xs text-muted-foreground p-2 block border border-muted rounded flex items-center">
+ <div className="text-xs text-muted-foreground p-2 border border-muted rounded flex items-center">
<span>{preview.error}</span>
{preview.missing_packages && (
<InstallPackageButton packages={preview.missing_packages} />
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsx
index 1afd830529..a0eaa8c700 100644
--- a/frontend/src/components/editor/output/JsonOutput.tsx
+++ b/frontend/src/components/editor/output/JsonOutput.tsx
@@ -65,6 +65,7 @@ const CopyButton: React.FC<DataItemProps<any>> = ({ value }) => {
"inline-flex ml-2 copy-button rounded w-6 h-3 justify-center items-center relative",
)}
aria-label="Copy to clipboard"
+ type="button"
>
{copied ? (
<CheckIcon className="w-5 h-5 absolute -top-0.5 p-1 hover:bg-muted rounded" />
diff --git a/frontend/src/components/ui/popover.tsx b/frontend/src/components/ui/popover.tsx
index 5e0063a603..3ee8d53406 100644
--- a/frontend/src/components/ui/popover.tsx
+++ b/frontend/src/components/ui/popover.tsx
@@ -10,6 +10,7 @@ const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverPortal = withFullScreenAsRoot(PopoverPrimitive.Portal);
+const PopoverClose = PopoverPrimitive.Close;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
@@ -44,4 +45,4 @@ const PopoverContent = React.forwardRef<
);
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
-export { Popover, PopoverTrigger, PopoverContent };
+export { Popover, PopoverTrigger, PopoverContent, PopoverClose };
diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsx
index 1c2627567f..959602c320 100644
--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx
+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx
@@ -5,7 +5,6 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";
import type { DataEditorProps } from "./data-editor/data-editor";
import { useAsyncData } from "@/hooks/useAsyncData";
import { vegaLoadData } from "./vega/loader";
-import { getVegaFieldTypes } from "./vega/utils";
import type { Setter } from "../types";
import { LoadingTable } from "@/components/data-table/loading-table";
import { Alert, AlertTitle } from "@/components/ui/alert";
@@ -15,7 +14,6 @@ import gridCss from "./data-editor/grid.css?inline";
import agGridCss from "ag-grid-community/styles/ag-grid.css?inline";
import agThemeCss from "ag-grid-community/styles/ag-theme-quartz.css?inline";
import { DATA_TYPES } from "@/core/kernel/messages";
-import { toFieldTypes } from "@/components/data-table/types";
type CsvURL = string;
type TableData<T> = T[] | CsvURL;
@@ -92,11 +90,10 @@ const LoadingDataEditor = (props: Props) => {
return props.data;
}
- const withoutExternalTypes = toFieldTypes(props.fieldTypes ?? []);
// Otherwise, load the data from the URL
return await vegaLoadData(
props.data,
- { type: "csv", parse: getVegaFieldTypes(withoutExternalTypes) },
+ { type: "json" },
{ handleBigIntAndNumberLike: true },
);
}, [props.fieldTypes, props.data]);
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index e7a69662fd..b882a98607 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -11,7 +11,6 @@ import { Alert, AlertTitle } from "@/components/ui/alert";
import { rpc } from "../core/rpc";
import { createPlugin } from "../core/builder";
import { vegaLoadData } from "./vega/loader";
-import { getVegaFieldTypes } from "./vega/utils";
import { Banner } from "./common/error-banner";
import { ColumnChartSpecModel } from "@/components/data-table/chart-spec-model";
import { ColumnChartContext } from "@/components/data-table/column-summary";
@@ -342,12 +341,10 @@ export const LoadingDataTableComponent = memo(
};
}
- const withoutExternalTypes = toFieldTypes(props.fieldTypes ?? []);
-
// Otherwise, load the data from the URL
tableData = await vegaLoadData(
tableData,
- { type: "csv", parse: getVegaFieldTypes(withoutExternalTypes) },
+ { type: "json" },
{ handleBigIntAndNumberLike: true },
);
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 89232d0547..efe330d881 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -97,12 +97,12 @@ class DefaultTableManager(TableManager[JsonTableData]):
return self._as_table_manager().to_csv(format_mapping)
- def to_json(self) -> bytes:
+ def to_json(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
if isinstance(self.data, dict) and not self.is_column_oriented:
return DefaultTableManager(
self._normalize_data(self.data)
- ).to_json()
- return self._as_table_manager().to_json()
+ ).to_json(format_mapping)
+ return self._as_table_manager().to_json(format_mapping)
def select_rows(self, indices: list[int]) -> DefaultTableManager:
if isinstance(self.data, dict):
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index f6b5210067..76ed356111 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -45,8 +45,10 @@ class IbisTableManagerFactory(TableManagerFactory):
) -> bytes:
return self._as_table_manager().to_csv(format_mapping)
- def to_json(self) -> bytes:
- return self._as_table_manager().to_json()
+ def to_json(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> bytes:
+ return self._as_table_manager().to_json(format_mapping)
def supports_download(self) -> bool:
return False
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 1785ff7fc1..4c26dda10c 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -8,6 +8,7 @@ from typing import Any, Optional, Union, cast
import narwhals.stable.v1 as nw
from narwhals.stable.v1.typing import IntoFrameT
+from marimo import _loggers
from marimo._data.models import ColumnSummary, ExternalDataType
from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
@@ -31,6 +32,8 @@ from marimo._utils.narwhals_utils import (
unwrap_py_scalar,
)
+LOGGER = _loggers.marimo_logger()
+
class NarwhalsTableManager(
TableManager[Union[nw.DataFrame[IntoFrameT], nw.LazyFrame[IntoFrameT]]]
@@ -62,8 +65,17 @@ class NarwhalsTableManager(
_data = self.apply_formatting(format_mapping).as_frame()
return dataframe_to_csv(_data).encode("utf-8")
- def to_json(self) -> bytes:
- csv_str = self.to_csv().decode("utf-8")
+ def to_json(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
+ try:
+ csv_str = self.to_csv(format_mapping=format_mapping).decode(
+ "utf-8"
+ )
+ except Exception as e:
+ LOGGER.debug(
+ f"Failed to use format mapping: {str(e)}, falling back to default"
+ )
+ csv_str = self.to_csv().decode("utf-8")
+
import csv
csv_reader = csv.DictReader(csv_str.splitlines())
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 6751dbc889..f937edb504 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -7,6 +7,7 @@ from typing import Any, Optional
import narwhals.stable.v1 as nw
+from marimo import _loggers
from marimo._data.models import ExternalDataType
from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
@@ -19,6 +20,8 @@ from marimo._plugins.ui._impl.tables.table_manager import (
TableManagerFactory,
)
+LOGGER = _loggers.marimo_logger()
+
class PandasTableManagerFactory(TableManagerFactory):
@staticmethod
@@ -33,6 +36,15 @@ class PandasTableManagerFactory(TableManagerFactory):
type = "pandas"
def __init__(self, data: pd.DataFrame) -> None:
+ if isinstance(data.columns, pd.MultiIndex):
+ LOGGER.debug(
+ "Multicolumn indexes aren't supported, converting to single index"
+ )
+ single_col_names = [
+ " x ".join(col) for col in data.columns
+ ]
+ data.columns = pd.Index(single_col_names)
+
self._original_data = data
super().__init__(nw.from_native(data))
@@ -61,11 +73,61 @@ class PandasTableManagerFactory(TableManagerFactory):
.encode("utf-8")
)
- def to_json(self) -> bytes:
- return self._original_data.to_json(orient="records").encode(
- "utf-8"
+ def to_json(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> bytes:
+ from pandas.api.types import (
+ is_complex_dtype,
+ is_timedelta64_dtype,
+ is_timedelta64_ns_dtype,
)
+ _data = self.apply_formatting(format_mapping)._original_data
+ result = _data.copy() # to avoid SettingWithCopyWarning
+ try:
+ for col in result.columns:
+ dtype = result[col].dtype
+ # Complex dtypes are converted to {'imag': num, 'real': num} by default
+ # We want to preserve the original display
+ if is_complex_dtype(dtype):
+ result[col] = result[col].apply(str)
+ if is_timedelta64_dtype(
+ dtype
+ ) or is_timedelta64_ns_dtype(dtype):
+ result[col] = result[col].apply(str)
+
+ except Exception as e:
+ LOGGER.error(
+ "Error handling complex or timedelta64 dtype",
+ exc_info=e,
+ )
+ return result.to_json(orient="records").encode("utf-8")
+
+ # Flatten indexes
+ if isinstance(result.index, pd.MultiIndex) or (
+ isinstance(result.index, pd.Index)
+ and not isinstance(result.index, pd.RangeIndex)
+ ):
+ unnamed_indexes = result.index.names[0] is None
+ index_levels = result.index.nlevels
+ result = result.reset_index()
+
+ if unnamed_indexes:
+ # We could rename, but it doesn't work cleanly for multi-col indexes
+ result.columns = pd.Index(
+ [""] + list(result.columns[1:])
+ )
+
+ if index_levels > 1:
+ LOGGER.warning(
+ "Indexes with more than one level are not supported properly, call reset_index() to flatten"
+ )
+
+ return result.to_json(
+ orient="records",
+ date_format="iso",
+ ).encode("utf-8")
+
def to_arrow_ipc(self) -> bytes:
out = io.BytesIO()
self._original_data.to_feather(out, compression="uncompressed")
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index c0c2a5a64a..2abfc66ee2 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -7,6 +7,7 @@ from typing import Any, Optional, Union
import narwhals.stable.v1 as nw
+from marimo import _loggers
from marimo._data.models import (
ExternalDataType,
)
@@ -21,6 +22,8 @@ from marimo._plugins.ui._impl.tables.table_manager import (
TableManagerFactory,
)
+LOGGER = _loggers.marimo_logger()
+
class PolarsTableManagerFactory(TableManagerFactory):
@staticmethod
@@ -89,30 +92,75 @@ class PolarsTableManagerFactory(TableManagerFactory):
).arr.join(",")
)
elif isinstance(dtype, pl.Object):
- import warnings
-
- with warnings.catch_warnings(record=True):
- result = result.with_columns(
- # As of writing this, cast(pl.String) doesn't work
- # for pl.Object types, so we use map_elements
- column.map_elements(
- str, return_dtype=pl.String
- )
- )
+ result = self._cast_object_to_string(
+ result, column
+ )
elif isinstance(dtype, pl.Duration):
- unit_map = {
- "ms": column.dt.total_milliseconds,
- "ns": column.dt.total_nanoseconds,
- "us": column.dt.total_microseconds,
- "s": column.dt.total_seconds,
- }
- if dtype.time_unit in unit_map:
- method = unit_map[dtype.time_unit]
- result = result.with_columns(method())
+ result = self._convert_time_to_string(
+ result, column
+ )
return result.write_csv().encode("utf-8")
- def to_json(self) -> bytes:
- return self.collect().write_json().encode("utf-8")
+ def to_json(
+ self, format_mapping: Optional[FormatMapping] = None
+ ) -> bytes:
+ result = self.apply_formatting(format_mapping).collect()
+ try:
+ for column in result.get_columns():
+ dtype = column.dtype
+ if isinstance(dtype, pl.Duration):
+ result = self._convert_time_to_string(
+ result, column
+ )
+ return result.write_json().encode("utf-8")
+ except (
+ BaseException
+ ): # Sometimes, polars throws a generic exception
+ LOGGER.debug(
+ "Failed to write json. Trying to convert columns to strings."
+ )
+ for column in result.get_columns():
+ dtype = column.dtype
+ if isinstance(dtype, pl.Object):
+ result = self._cast_object_to_string(
+ result, column
+ )
+ elif str(dtype) == "Int128":
+ # Use string comparison because pl.Int128 doesn't exist on older versions
+ # As of writing this, Int128 is not supported by polars
+ LOGGER.warning(
+ "Column %s is of type Int128, which is not supported. Converting to string.",
+ column.name,
+ )
+ result = result.with_columns(
+ column.cast(pl.String)
+ )
+ elif isinstance(dtype, pl.Duration):
+ result = self._convert_time_to_string(
+ result, column
+ )
+
+ return result.write_json().encode("utf-8")
+
+ def _convert_time_to_string(
+ self, result: pl.DataFrame, column: pl.Series
+ ) -> pl.DataFrame:
+ # Converts to human readable format
+ return result.with_columns(
+ column.dt.to_string(format="polars")
+ )
+
+ def _cast_object_to_string(
+ self, df: pl.DataFrame, column: pl.Series
+ ) -> pl.DataFrame:
+ import warnings
+
+ with warnings.catch_warnings(record=True):
+ return df.with_columns(
+ # As of writing this, cast(pl.String) doesn't work
+ # for pl.Object types, so we use map_elements
+ column.map_elements(str, return_dtype=pl.String)
+ )
def apply_formatting(
self, format_mapping: Optional[FormatMapping]
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index 9b8b96cad1..45a0ccf6d5 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -62,10 +62,10 @@ class TableManager(abc.ABC, Generic[T]):
"""
The best way to represent the data in a table as JSON.
- By default, this method calls `to_csv` and returns the result as
- a string.
+ By default, this method calls `to_json` and returns the result as
+ a string. `to_json` supports most data types (e.g. nested lists)
"""
- return mo_data.csv(self.to_csv(format_mapping)).url
+ return mo_data.json(self.to_json(format_mapping)).url
def supports_download(self) -> bool:
return True
@@ -103,7 +103,7 @@ class TableManager(abc.ABC, Generic[T]):
raise NotImplementedError("Arrow format not supported")
@abc.abstractmethod
- def to_json(self) -> bytes:
+ def to_json(self, format_mapping: Optional[FormatMapping] = None) -> bytes:
pass
@abc.abstractmethod
diff --git a/marimo/_smoke_tests/tables/complex_types.py b/marimo/_smoke_tests/tables/complex_types.py
index 18f0689bed..f3f7bab293 100644
--- a/marimo/_smoke_tests/tables/complex_types.py
+++ b/marimo/_smoke_tests/tables/complex_types.py
@@ -1,12 +1,13 @@
import marimo
-__generated_with = "0.11.5"
+__generated_with = "0.11.20"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
def _():
import polars as pl
+ import numpy as np
from datetime import datetime, date, time
import marimo as mo
@@ -35,11 +36,21 @@ def _():
"lists": pl.Series(
"lists", [[1, 2], [3, 4], [5, 6]], dtype=pl.List(pl.Int64)
),
+ "nested_lists": pl.Series(
+ "nested_lists",
+ [[[1, 2]], [[3, 4]], [[5, 6]]],
+ dtype=pl.List(pl.List(pl.Int64)),
+ ),
"arrays": pl.Series(
"arrays",
[[1, 2], [3, 4], [5, 6]],
dtype=pl.Array(pl.Int64, shape=(2,)),
),
+ "nested_arrays": pl.Series(
+ "nested_arrays",
+ [[[1, 2]], [[3, 4]], [[5, 6]]],
+ dtype=pl.Array(pl.Array(pl.Int64, shape=(2,)), shape=(1,)),
+ ),
# Objects
"sets": pl.Series(
"sets", [set([1, 2]), set([3, 4]), set([5, 6])], dtype=pl.Object
@@ -54,6 +65,19 @@ def _():
[{"a": 1, "b": 2}, {"c": 3, "d": 4}, {"e": 5, "f": 6}],
dtype=pl.Struct,
),
+ # Mixed
+ "structs_with_list": pl.Series(
+ "mixed",
+ [{"a": [1, 2], "b": 2}, {"a": [3, 4], "b": 4}, [5, 6]],
+ ),
+ "list_with_structs": pl.Series(
+ "list_with_structs",
+ [
+ [{"a": 1}, {"c": 3}],
+ [{"e": 5}],
+ [],
+ ],
+ ),
# Nulls
"nulls": pl.Series("nulls", [None, None, None], dtype=pl.Utf8),
# Complex
@@ -65,7 +89,7 @@ def _():
}
)
mo.ui.table(df)
- return date, datetime, df, mo, pl, time
+ return date, datetime, df, mo, np, pl, time
@app.cell
@@ -75,6 +99,18 @@ def _(df):
return (pandas,)
+def _(mo, pd, pl):
+ additional_types_pd = pd.DataFrame(
+ {"complex": [1 + 2j, 2 + 3j], "bigint": [2**64, 2**127]}
+ )
+ additional_types_pl = pl.DataFrame(
+ {"complex": [1 + 2j, 2 + 3j], "bigint": [2**64, 2**65]}
+ )
+ mo.vstack([additional_types_pd, additional_types_pl])
+ return additional_types_pd, additional_types_pl
+
+
@app.cell
def _():
# arrow = df.to_arrow()
diff --git a/marimo/_smoke_tests/tables/pandas_multi_idx.py b/marimo/_smoke_tests/tables/pandas_multi_idx.py
new file mode 100644
index 0000000000..503f4b89ff
--- /dev/null
+++ b/marimo/_smoke_tests/tables/pandas_multi_idx.py
@@ -0,0 +1,53 @@
+import marimo
+
+__generated_with = "0.11.20"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ return mo, pd
+
+
+def _(pd):
+ arrays = [
+ ["bar", "bar"],
+ ["one", "two"],
+ ]
+ tuples = list(zip(*arrays))
+ index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
+ named_indexes = pd.Series([1, 2], index=index)
+ named_indexes
+ return arrays, index, named_indexes, tuples
+
+
+def _(pd):
+ unnamed_indexes = pd.concat(
+ {
+ "a": pd.DataFrame({"foo": [1]}, index=["hello"]),
+ "b": pd.DataFrame({"baz": [2.0]}, index=["world"]),
+ }
+ )
+ unnamed_indexes
+ # unnamed_indexes.reset_index() # this works
+ return (unnamed_indexes,)
+
+
+def _(pd):
+ cols = pd.MultiIndex.from_arrays(
+ [["basic_amt"] * 2, ["NSW", "QLD"]], names=[None, "Faculty"]
+ )
+ idx = pd.Index(["All", "Full"])
+ column_multi_idx = pd.DataFrame([(1, 1), (0, 1)], index=idx, columns=cols)
+
+ column_multi_idx
+ return cols, column_multi_idx, idx
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/tables/polars_duration.py b/marimo/_smoke_tests/tables/polars_duration.py
index da394b9697..43d5cd7fb9 100644
--- a/marimo/_smoke_tests/tables/polars_duration.py
+++ b/marimo/_smoke_tests/tables/polars_duration.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.10.6"
+__generated_with = "0.11.20"
app = marimo.App(width="medium")
diff --git a/pyproject.toml b/pyproject.toml
index 39053f89ea..a031603dd6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -244,7 +244,7 @@ extra-dependencies = [
"pyarrow",
"pyarrow_hotfix",
"altair>=5.4.0",
- "polars~=1.9.0",
+ "polars~=1.24.0",
"sqlglot>=23.4",
"sqlalchemy>=2.0.38",
"pandas>=1.5.3",
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 6f746b4ef0..6d0861696b 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -136,8 +136,10 @@ class TestDataframes:
subject = ui.dataframe(df, page_size=1)
result = subject._get_dataframe(EmptyArgs())
assert result.total_rows == 3
- assert result.url == "data:text/csv;base64,MSwyCjEsYQo="
-
+ assert (
+ result.url
+ == "data:application/json;base64,W3siMSI6MSwiMiI6ImEifV0="
+ )
# search
search_result = subject._search(
SearchTableArgs(page_size=1, page_number=0)
@@ -149,7 +151,10 @@ class TestDataframes:
subject = ui.dataframe(df, page_size=2)
result = subject._get_dataframe(EmptyArgs())
assert result.total_rows == 3
- assert result.url == "data:text/csv;base64,MSwyCjEsYQoyLGEK"
+ assert (
+ result.url
+ == "data:application/json;base64,W3siMSI6MSwiMiI6ImEifSx7IjEiOjIsIjIiOiJhIn1d"
+ )
# search
search_result = subject._search(
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.json b/tests/_plugins/ui/_impl/tables/snapshots/ibis.json
index bf01409a78..14aeb7cfb3 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.json
@@ -4,8 +4,8 @@
"bool": true,
"int": 1,
"float": 1.0,
- "date": 1609459200000,
- "datetime": 1609459200,
+ "date": "2021-01-01T00:00:00.000",
+ "datetime": "2021-01-01T00:00:00.000",
"time": "01:02:03",
"nulls": null
},
@@ -14,8 +14,8 @@
"bool": false,
"int": 2,
"float": 2.0,
- "date": 1609545600000,
- "datetime": 1609545600,
+ "date": "2021-01-02T00:00:00.000",
+ "datetime": "2021-01-02T00:00:00.000",
"time": "04:05:06",
"nulls": "data"
},
@@ -24,8 +24,8 @@
"bool": true,
"int": 3,
"float": 3.0,
- "date": 1609632000000,
- "datetime": 1609632000,
+ "date": "2021-01-03T00:00:00.000",
+ "datetime": "2021-01-03T00:00:00.000",
"time": "07:08:09",
"nulls": null
}
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/pandas.json b/tests/_plugins/ui/_impl/tables/snapshots/pandas.json
index 7cb9b1c872..a548b0452f 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/pandas.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/pandas.json
@@ -4,16 +4,16 @@
"bool": true,
"int": 1,
"float": 1.0,
- "datetime": 1609459200000,
- "date": 1609459200000,
+ "datetime": "2021-01-01T00:00:00.000",
+ "date": "2021-01-01T00:00:00.000",
"struct": { "a": 1, "b": 2 },
"list": [1, 2],
"nulls": null,
"category": "cat",
"set": [1, 2],
- "imaginary": { "imag": 2.0, "real": 1.0 },
+ "imaginary": "(1+2j)",
"time": "12:30:00",
- "duration": 86400000,
+ "duration": "1 days 00:00:00",
"mixed_list": [1, "two"]
},
{
@@ -21,16 +21,16 @@
"bool": false,
"int": 2,
"float": 2.0,
- "datetime": 1609545600000,
- "date": 1609545600000,
+ "datetime": "2021-01-02T00:00:00.000",
+ "date": "2021-01-02T00:00:00.000",
"struct": { "a": 3, "b": 4 },
"list": [3, 4],
"nulls": "data",
"category": "dog",
"set": [3, 4],
- "imaginary": { "imag": 4.0, "real": 3.0 },
+ "imaginary": "(3+4j)",
"time": "13:45:00",
- "duration": 172800000,
+ "duration": "2 days 00:00:00",
"mixed_list": [3.0, false]
},
{
@@ -38,16 +38,16 @@
"bool": true,
"int": 3,
"float": 3.0,
- "datetime": 1609632000000,
- "date": 1609632000000,
+ "datetime": "2021-01-03T00:00:00.000",
+ "date": "2021-01-03T00:00:00.000",
"struct": { "a": 5, "b": 6 },
"list": [5, 6],
"nulls": null,
"category": "mouse",
"set": [5, 6],
- "imaginary": { "imag": 6.0, "real": 5.0 },
+ "imaginary": "(5+6j)",
"time": "14:15:00",
- "duration": 259200000,
- "mixed_list": [null, 1609459200000]
+ "duration": "3 days 00:00:00",
+ "mixed_list": [null, "2021-01-01T00:00:00.000"]
}
]
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
index 69e813ad37..44fd6f001f 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
@@ -1,4 +1,4 @@
-strings,bool,int,float,datetime,date,struct,list,array,nulls,category,set,imaginary,time,duration,mixed_list
-a,true,1,1.0,2021-01-01T00:00:00.000000,2021-01-01,"{""a"":1,""b"":2}","1,2",1,,cat,"{1, 2}",(1+2j),12:30:00.000000000,86400000000,"1,two"
-b,false,2,2.0,2021-01-02T00:00:00.000000,2021-01-02,"{""a"":3,""b"":4}","3,4",2,data,dog,"{3, 4}",(3+4j),13:45:00.000000000,172800000000,"3.0,0.0"
-c,true,3,3.0,2021-01-03T00:00:00.000000,2021-01-03,"{""a"":5,""b"":6}","5,6",3,,mouse,"{5, 6}",(5+6j),14:15:00.000000000,259200000000,2021-01-01 00:00:00.000000
+strings,bool,int,large_int,float,datetime,date,struct,list,array,nulls,category,set,imaginary,time,duration,mixed_list
+a,true,1,18446744073709551616,1.0,2021-01-01T00:00:00.000000,2021-01-01,"{""a"":1,""b"":2}","1,2",1,,cat,"{1, 2}",(1+2j),12:30:00.000000000,1d,"1,two"
+b,false,2,36893488147419103233,2.0,2021-01-02T00:00:00.000000,2021-01-02,"{""a"":3,""b"":4}","3,4",2,data,dog,"{3, 4}",(3+4j),13:45:00.000000000,315µs,"3.0,0.0"
+c,true,3,73786976294838206466,3.0,2021-01-03T00:00:00.000000,2021-01-03,"{""a"":5,""b"":6}","5,6",3,,mouse,"{5, 6}",(5+6j),14:15:00.000000000,2h 30m,2021-01-01 00:00:00.000000
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
index f8107f389a..9450e34ce8 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
@@ -2,11 +2,14 @@
["strings", ["string", "str"]],
["bool", ["boolean", "bool"]],
["int", ["integer", "i64"]],
+ ["large_int", ["integer", "i128"]],
["float", ["number", "f64"]],
["datetime", ["datetime", "datetime[\u03bcs]"]],
["date", ["date", "date"]],
["struct", ["unknown", "struct[2]"]],
["list", ["unknown", "list[i64]"]],
+ ["nested_lists", ["unknown", "list[list[i64]]"]],
+ ["nested_arrays", ["unknown", "array[i64, (1, 2)]"]],
["array", ["unknown", "array[i64, 1]"]],
["nulls", ["string", "str"]],
["category", ["string", "cat"]],
@@ -14,5 +17,7 @@
["imaginary", ["unknown", "object"]],
["time", ["time", "Time"]],
["duration", ["number", "duration[\u03bcs]"]],
- ["mixed_list", ["unknown", "list[str]"]]
+ ["mixed_list", ["unknown", "list[str]"]],
+ ["structs_with_list", ["unknown", "struct[2]"]],
+ ["list_with_structs", ["unknown", "list[struct[2]]"]]
]
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
index 9c165e5184..c8dadd231c 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
@@ -3,45 +3,69 @@
"strings": "a",
"bool": true,
"int": 1,
+ "large_int": "18446744073709551616",
"float": 1.0,
"datetime": "2021-01-01 00:00:00",
"date": "2021-01-01",
"struct": { "a": 1, "b": 2 },
"list": [1, 2],
+ "nested_lists": [[1, 2]],
+ "nested_arrays": [[1, 2]],
"array": [1],
"nulls": null,
"category": "cat",
- "duration": "PT86400S",
- "mixed_list": ["1", "two"]
+ "set": "{1, 2}",
+ "imaginary": "(1+2j)",
+ "time": "12:30:00",
+ "duration": "1d",
+ "mixed_list": ["1", "two"],
+ "structs_with_list": { "a": [1, 2], "b": 2 },
+ "list_with_structs": [{ "a": 1, "c": null }, { "a": null, "c": 3 }]
},
{
"strings": "b",
"bool": false,
"int": 2,
+ "large_int": "36893488147419103233",
"float": 2.0,
"datetime": "2021-01-02 00:00:00",
"date": "2021-01-02",
"struct": { "a": 3, "b": 4 },
"list": [3, 4],
+ "nested_lists": [[3, 4]],
+ "nested_arrays": [[3, 4]],
"array": [2],
"nulls": "data",
"category": "dog",
- "duration": "PT172800S",
- "mixed_list": ["3.0", "0.0"]
+ "set": "{3, 4}",
+ "imaginary": "(3+4j)",
+ "time": "13:45:00",
+ "duration": "315µs",
+ "mixed_list": ["3.0", "0.0"],
+ "structs_with_list": { "a": [3, 4], "b": 4 },
+ "list_with_structs": [{ "a": null, "c": null }]
},
{
"strings": "c",
"bool": true,
"int": 3,
+ "large_int": "73786976294838206466",
"float": 3.0,
"datetime": "2021-01-03 00:00:00",
"date": "2021-01-03",
"struct": { "a": 5, "b": 6 },
"list": [5, 6],
+ "nested_lists": [[5, 6]],
+ "nested_arrays": [[5, 6]],
"array": [3],
"nulls": null,
"category": "mouse",
- "duration": "PT259200S",
- "mixed_list": [null, "2021-01-01 00:00:00.000000"]
+ "set": "{5, 6}",
+ "imaginary": "(5+6j)",
+ "time": "14:15:00",
+ "duration": "2h 30m",
+ "mixed_list": [null, "2021-01-01 00:00:00.000000"],
+ "structs_with_list": { "a": null, "b": null },
+ "list_with_structs": []
}
]
diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
index d0477eb03f..76df55f067 100644
--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py
@@ -89,6 +89,18 @@ class TestIbisTableManagerFactory(unittest.TestCase):
assert isinstance(data, bytes)
snapshot("ibis.json", data.decode("utf-8"))
+ def test_to_json_format_mapping(self) -> None:
+ import ibis
+
+ table = ibis.memtable({"int": [1, 2, 3]})
+ data = self.factory.create()(table)
+
+ format_mapping = {"int": lambda x: x * 2}
+ json_data = data.to_json(format_mapping)
+
+ json_object = json.loads(json_data.decode("utf-8"))
+ assert json_object == [{"int": 2}, {"int": 4}, {"int": 6}]
+
def test_complex_data_field_types(self) -> None:
complex_data = self.get_complex_data()
field_types = complex_data.get_field_types()
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index a6450e5974..0f5b9d6d19 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -753,6 +753,27 @@ def test_to_json(df: Any) -> None:
assert isinstance(manager.to_json(), bytes)
+ reason="Format mapping is not supported when converting to JSON"
+)
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "A": [1, 2, 3],
+ }
+ ),
+)
+def test_to_json_format_mapping(df: Any) -> None:
+ format_mapping = {"A": lambda x: x * 2}
+ manager = NarwhalsTableManager.from_dataframe(df)
+ json_data = manager.to_json(format_mapping)
+
+ json_object = json.loads(json_data)
+ assert json_object == [{"A": 2}, {"A": 4}, {"A": 6}]
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 72d6c9cd13..fbb2fe3787 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -151,16 +151,134 @@ class TestPandasTableManager(unittest.TestCase):
assert isinstance(data, bytes)
snapshot("pandas.csv", data.decode("utf-8"))
+ def factory_create_json_from_df(self, df: Any) -> Any:
+ if isinstance(df, pd.DataFrame):
+ manager = self.factory.create()(df)
+ return json.loads(manager.to_json().decode("utf-8"))
+
def test_to_json(self) -> None:
- expected_json = self.data.to_json(orient="records").encode("utf-8")
+ expected_json = self.data.to_json(
+ orient="records", date_format="iso"
+ ).encode("utf-8")
assert self.manager.to_json() == expected_json
+ def test_to_json_format_mapping(self) -> None:
+ expected_json = (
+ self.data.assign(A=self.data["A"] * 2)
+ .to_json(orient="records", date_format="iso")
+ .encode("utf-8")
+ )
+ format_mapping = {"A": lambda x: x * 2}
+ assert self.manager.to_json(format_mapping) == expected_json, (
+ "Format mapping not applied"
+ )
+
+ def test_to_json_datetime_handling(self) -> None:
+ timestamps = pd.DataFrame(
+ {
+ "timestamp": [pd.to_datetime("2024-12-17")],
+ "timestamp_with_timezone": [
+ pd.to_datetime("2024-12-17").tz_localize("UTC")
+ ],
+ }
+ )
+ json_data = self.factory_create_json_from_df(timestamps)
+
+ assert json_data[0]["timestamp"] == "2024-12-17T00:00:00.000"
+ assert (
+ json_data[0]["timestamp_with_timezone"]
+ == "2024-12-17T00:00:00.000Z"
+ )
+
+ def test_to_json_complex_number_handling(self) -> None:
+ df = pd.DataFrame({"complex": [1 + 2j]})
+ json_data = self.factory_create_json_from_df(df)
+ assert json_data[0]["complex"] == "(1+2j)"
+
+ @pytest.mark.skipif(
+ not DependencyManager.numpy.has(),
+ reason="numpy not installed",
+ )
+ def test_to_json_numpy_complex_handling(self) -> None:
+ import numpy as np
+
+ df = pd.DataFrame({"complex": np.array([1 + 2j])})
+ json_data = self.factory_create_json_from_df(df)
+ assert json_data[0]["complex"] == "(1+2j)"
+
def test_to_json_complex(self) -> None:
complex_data = self.get_complex_data()
data = complex_data.to_json()
assert isinstance(data, bytes)
snapshot("pandas.json", data.decode("utf-8"))
+ def test_to_json_index(self) -> None:
+ data = pd.DataFrame({"a": [1, 2, 3]}, index=["c", "d", "e"])
+ json_data = self.factory_create_json_from_df(data)
+ assert json_data == [
+ {"": "c", "a": 1},
+ {"": "d", "a": 2},
+ {"": "e", "a": 3},
+ ]
+
+ # Named index
+ data = pd.DataFrame(
+ {"a": [1, 2, 3]}, index=pd.Index(["c", "d", "e"], name="index")
+ )
+ json_data = self.factory_create_json_from_df(data)
+ assert json_data == [
+ {"index": "c", "a": 1},
+ {"index": "d", "a": 2},
+ {"index": "e", "a": 3},
+ ]
+
+ def test_to_json_multi_index(self) -> None:
+ # Named index
+ data = pd.DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [4, 5, 6],
+ },
+ index=pd.MultiIndex.from_tuples(
+ [("x", 1), ("y", 2), ("z", 3)], names=["X", "Y"]
+ ),
+ )
+ json_data = self.factory_create_json_from_df(data)
+ assert json_data == [
+ {"X": "x", "Y": 1, "a": 1, "b": 4},
+ {"X": "y", "Y": 2, "a": 2, "b": 5},
+ {"X": "z", "Y": 3, "a": 3, "b": 6},
+ ]
+
+ @pytest.mark.xfail(reason="Implementation not yet supported")
+ def test_to_json_multi_index_unnamed(self) -> None:
+ data = pd.DataFrame(
+ {
+ "a": [1, 2, 3],
+ "b": [4, 5, 6],
+ },
+ index=pd.MultiIndex.from_tuples([("x", 1), ("y", 2), ("z", 3)]),
+ )
+ json_data = self.factory_create_json_from_df(data)
+ assert json_data == [
+ {"level_0": "x", "level_1": 1, "a": 1, "b": 4},
+ {"level_0": "y", "level_1": 2, "a": 2, "b": 5},
+ {"level_0": "z", "level_1": 3, "a": 3, "b": 6},
+ ]
+
+ def test_to_json_multi_col_index(self) -> None:
+ cols = pd.MultiIndex.from_arrays(
+ [["basic_amt"] * 2, ["NSW", "QLD"]], names=[None, "Faculty"]
+ )
+ idx = pd.Index(["All", "Full"])
+ data = pd.DataFrame([(1, 1), (0, 1)], index=idx, columns=cols)
+
+ json_data = self.factory_create_json_from_df(data)
+ assert json_data == [
+ {"": "All", "basic_amt x NSW": 1, "basic_amt x QLD": 1},
+ {"": "Full", "basic_amt x NSW": 0, "basic_amt x QLD": 1},
+ ]
+
def test_complex_data_field_types(self) -> None:
complex_data = self.get_complex_data()
field_types = complex_data.get_field_types()
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index e44fe026f4..d3d6654612 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -15,6 +15,7 @@ from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
from marimo._plugins.ui._impl.tables.table_manager import TableManager
+from marimo._utils.platform import is_windows
from tests.mocks import snapshotter
HAS_DEPS = DependencyManager.polars.has()
@@ -43,6 +44,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"strings": ["a", "b", "c"],
"bool": [True, False, True],
"int": [1, 2, 3],
+ "large_int": [2**64, 2**65 + 1, 2**66 + 2],
"float": [1.0, 2.0, 3.0],
"datetime": [
datetime.datetime(2021, 1, 1),
@@ -62,6 +64,14 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
"list": pl.Series(
[[1, 2], [3, 4], [5, 6]], dtype=pl.List(pl.Int64)
),
+ "nested_lists": pl.Series(
+ [[[1, 2]], [[3, 4]], [[5, 6]]],
+ dtype=pl.List(pl.List(pl.Int64)),
+ ),
+ "nested_arrays": pl.Series(
+ [[[1, 2]], [[3, 4]], [[5, 6]]],
+ dtype=pl.Array(pl.Array(pl.Int64, shape=(2,)), shape=(1,)),
+ ),
"array": pl.Series(
[[1], [2], [3]], dtype=pl.Array(pl.Int64, 1)
),
@@ -78,14 +88,26 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
],
"duration": [
datetime.timedelta(days=1),
- datetime.timedelta(days=2),
- datetime.timedelta(days=3),
+ datetime.timedelta(microseconds=315),
+ datetime.timedelta(hours=2, minutes=30),
],
"mixed_list": [
[1, "two"],
[3.0, False],
[None, datetime.datetime(2021, 1, 1)],
],
+ "structs_with_list": pl.Series(
+ "mixed",
+ [{"a": [1, 2], "b": 2}, {"a": [3, 4], "b": 4}, [5, 6]],
+ ),
+ "list_with_structs": pl.Series(
+ "list_with_structs",
+ [
+ [{"a": 1}, {"c": 3}],
+ [{"e": 5}],
+ [],
+ ],
+ ),
},
strict=False,
)
@@ -122,9 +144,26 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
def test_to_csv(self) -> None:
assert isinstance(self.manager.to_csv(), bytes)
+ @pytest.mark.skipif(
+ is_windows(),
+ reason="Windows doesn't show microseconds unicode properly",
+ )
def test_to_csv_complex(self) -> None:
complex_data = self.get_complex_data()
- data = complex_data.to_csv()
+ # CSV does not support nested data types
+ columns = [
+ col
+ for col in complex_data.get_column_names()
+ if col
+ not in [
+ "nested_lists",
+ "nested_arrays",
+ "list_with_structs",
+ "structs_with_list",
+ ]
+ ]
+ manager = complex_data.select_columns(columns)
+ data = manager.to_csv()
assert isinstance(data, bytes)
snapshot("polars.csv", data.decode("utf-8"))
@@ -142,24 +181,33 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
def test_to_json(self) -> None:
assert isinstance(self.manager.to_json(), bytes)
+ def test_to_json_apply_format_mapping(self) -> None:
+ import polars as pl
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: x * 2,
+ }
+ json_bytes = self.manager.to_json(format_mapping)
+ assert isinstance(json_bytes, bytes)
+
+ formatted_data = pl.read_json(json_bytes)
+ assert formatted_data["A"].to_list() == [2, 4, 6]
+
+ @pytest.mark.skipif(
+ is_windows(),
+ reason="Windows doesn't show microseconds unicode properly",
+ )
def test_to_json_complex(self) -> None:
complex_data = self.get_complex_data()
- # pl.Time and pl.Object are not supported in JSON
- other_columns = [
- col
- for col in complex_data.get_column_names()
- if col
- not in [
- "time",
- "set",
- "imaginary",
- ]
- ]
- manager = complex_data.select_columns(other_columns)
- data = manager.to_json()
+ data = complex_data.to_json()
assert isinstance(data, bytes)
snapshot("polars.json", data.decode("utf-8"))
+ json_data = json.loads(data)
+ assert json_data[0]["duration"] == "1d"
+ assert json_data[1]["duration"] == "315µs"
+ assert json_data[2]["duration"] == "2h 30m"
+
def test_complex_data_field_types(self) -> None:
complex_data = self.get_complex_data()
field_types = complex_data.get_field_types()
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index bf35f32d29..fb206635a3 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import json
from datetime import date
from typing import Any
@@ -736,8 +737,8 @@ def test_can_get_second_page_with_search_df(df: Any) -> None:
)
)
mime_type, data = from_data_uri(result.data)
- assert mime_type == "text/csv"
- data = pl.read_csv(data)
+ assert mime_type == "application/json"
+ data = pl.read_json(data)
assert len(data) == 5
assert int(data["a"][0]) == 23
assert int(data["a"][-1]) == 27
@@ -850,7 +851,7 @@ def test__get_column_summaries_after_search_df() -> None:
summaries = table._get_column_summaries(EmptyArgs())
assert summaries.is_disabled is False
assert isinstance(summaries.data, str)
- assert summaries.data.startswith("data:text/csv;base64,")
+ assert summaries.data.startswith("data:application/json;base64,")
assert summaries.summaries[0].min == 0
assert summaries.summaries[0].max == 19
@@ -865,7 +866,7 @@ def test__get_column_summaries_after_search_df() -> None:
summaries = table._get_column_summaries(EmptyArgs())
assert summaries.is_disabled is False
assert isinstance(summaries.data, str)
- assert summaries.data.startswith("data:text/csv;base64,")
+ assert summaries.data.startswith("data:application/json;base64,")
# We don't have column summaries for non-dataframe data
assert summaries.summaries[0].min == 2
assert summaries.summaries[0].max == 12
@@ -1272,8 +1273,9 @@ def test_column_clamping_with_polars():
# Check that the table is clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- headers = csv.split("\n")[0].split(",")
+ json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ headers = json_data[0].keys()
assert len(headers) == 50 # 50 columns
assert len(table._component_args["field-types"]) == 50
@@ -1282,8 +1284,9 @@ def test_column_clamping_with_polars():
# Check that the table is clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- headers = csv.split("\n")[0].split(",")
+ json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ headers = json_data[0].keys()
assert len(headers) == 40 # 40 columns
assert len(table._component_args["field-types"]) == 40
@@ -1292,8 +1295,9 @@ def test_column_clamping_with_polars():
# Check that the table is not clamped
assert len(table._manager.get_column_names()) == 60
assert table._component_args["total-columns"] == 60
- csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")
- headers = csv.split("\n")[0].split(",")
+ json_data = from_data_uri(table._component_args["data"])[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ headers = json_data[0].keys()
assert len(headers) == 61 # 60 columns + 1 selection column
assert len(table._component_args["field-types"]) == 60