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.

fix(table): open the JSON viewer for str columns that hold JSON documents (#10629)

Kiran Gadhave727f2a429815
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsx
index 831598c4c7..a2561ac1fb 100644
--- a/frontend/src/components/data-table/__tests__/columns.test.tsx
+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx
@@ -3,7 +3,7 @@
import type { Column } from "@tanstack/react-table";
import { fireEvent, render, waitFor } from "@testing-library/react";
import { I18nProvider } from "react-aria";
-import { describe, expect, it, test, vi } from "vitest";
+import { beforeAll, describe, expect, it, test, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Logger } from "@/utils/Logger";
import { parseContent } from "@/utils/url-parser";
@@ -933,6 +933,128 @@ describe("renderCellValue with string + edge whitespace", () => {
});
});
+describe("renderCellValue with JSON document strings", () => {
+ beforeAll(() => {
+ // JsonViewer reads the color scheme through matchMedia, which jsdom
+ // does not implement.
+ Object.defineProperty(window, "matchMedia", {
+ writable: true,
+ value: vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+ });
+
+ const createMockStringColumn = () =>
+ ({
+ id: "json_data",
+ columnDef: {
+ meta: {
+ dataType: "string" as const,
+ dtype: "str",
+ },
+ },
+ getColumnFormatting: () => undefined,
+ getColumnWrapping: () => undefined,
+ applyColumnFormatting: (value: unknown) => value,
+ }) as unknown as Column<unknown>;
+
+ const renderCell = (value: string) => {
+ const result = renderCellValue({
+ column: createMockStringColumn(),
+ renderValue: () => value,
+ getValue: () => value,
+ selectCell: undefined,
+ cellStyles: "",
+ });
+ return render(
+ <I18nProvider locale="en-US">
+ <TooltipProvider>{result}</TooltipProvider>
+ </I18nProvider>,
+ );
+ };
+
+ it("opens the JSON viewer for a str cell that holds a JSON object", () => {
+ const value =
+ '{"vendor":"ACME","attachments":[{"name":"inv.pdf","url":"https://example.com/p/AAA"}]}';
+ const { container } = renderCell(value);
+
+ const trigger = container.querySelector("button");
+ expect(trigger).toBeTruthy();
+ fireEvent.click(trigger!);
+
+ // Popover content mounts in a portal, so query the document.
+ expect(document.querySelector(".marimo-json-output")).toBeTruthy();
+ expect(document.body.textContent).toContain('"vendor":"ACME"');
+ });
+
+ it("opens the JSON viewer for a str cell that holds a JSON array", () => {
+ const value = '[{"name":"inv.pdf","url":"https://example.com/p/AAA"}]';
+ const { container } = renderCell(value);
+
+ const trigger = container.querySelector("button");
+ expect(trigger).toBeTruthy();
+ fireEvent.click(trigger!);
+
+ expect(document.querySelector(".marimo-json-output")).toBeTruthy();
+ expect(document.body.textContent).toContain('"name":"inv.pdf"');
+ });
+
+ it("opens the JSON viewer when the JSON document has edge whitespace", () => {
+ const { container } = renderCell(' {"a": 1} ');
+
+ const trigger = container.querySelector("button");
+ expect(trigger).toBeTruthy();
+ fireEvent.click(trigger!);
+
+ expect(document.querySelector(".marimo-json-output")).toBeTruthy();
+ });
+
+ it("keeps a Python repr as inline text", () => {
+ const value = "{'vendor': 'ACME'}";
+ const { container } = renderCell(value);
+
+ expect(container.querySelector("button")).toBeNull();
+ expect(container.textContent).toBe(value);
+ });
+
+ it("keeps a truncated JSON document as inline text", () => {
+ const value = '{"vendor":"ACME","attachments":';
+ const { container } = renderCell(value);
+
+ expect(container.querySelector("button")).toBeNull();
+ expect(container.textContent).toBe(value);
+ });
+
+ it("keeps JSON scalar strings as inline text", () => {
+ const value = '"hello"';
+ const { container } = renderCell(value);
+
+ expect(container.querySelector("button")).toBeNull();
+ expect(container.textContent).toBe(value);
+ });
+
+ it("keeps the text popout for long strings that are not JSON", () => {
+ const value =
+ "This long plain sentence exceeds the fifty character popout threshold.";
+ const { container } = renderCell(value);
+
+ const trigger = container.querySelector("button");
+ expect(trigger).toBeTruthy();
+ fireEvent.click(trigger!);
+
+ expect(document.querySelector(".marimo-json-output")).toBeNull();
+ expect(document.body.textContent).toContain(value);
+ });
+});
+
describe("renderCellValue with boolean values", () => {
const createMockColumn = () =>
({
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index a42b46d4fc..7818a5d001 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -487,6 +487,28 @@ const PopoutColumn = ({
);
};
+/**
+ * Parse a string that holds a JSON object or array document.
+ * Returns `undefined` for everything else, including JSON scalars,
+ * so ordinary text keeps its plain rendering.
+ */
+function parseJsonDocument(text: string): unknown {
+ const trimmedText = text.trim();
+
+ const first = trimmedText[0];
+ const last = trimmedText[trimmedText.length - 1];
+ const isBracketPair =
+ (first === "{" && last === "}") || (first === "[" && last === "]");
+ if (!isBracketPair) {
+ return undefined;
+ }
+ try {
+ return JSON.parse(trimmedText) as unknown;
+ } catch {
+ return undefined;
+ }
+}
+
function isPrimitiveOrNullish(value: unknown): boolean {
if (value == null) {
return true;
@@ -671,6 +693,28 @@ export function renderCellValue<TData, TValue>({
splitLeadingTrailingWhitespace(stringValue);
const hasEdgeWhitespace = leading.length > 0 || trailing.length > 0;
+ // A str cell that holds a JSON document opens the same JSON viewer as
+ // native list/struct cells.
+ const jsonDocument = parseJsonDocument(middle);
+ if (jsonDocument !== undefined) {
+ return (
+ <PopoutColumn
+ cellStyles={cellStyles}
+ selectCell={selectCell}
+ rawStringValue={stringValue}
+ edges={{ leading, trailing }}
+ wrapped={isWrapped}
+ >
+ <JsonOutput
+ data={jsonDocument}
+ format="tree"
+ valueTypes="json"
+ className="max-h-64"
+ />
+ </PopoutColumn>
+ );
+ }
+
// Parse only the inner content for URL detection so URLDetector doesn't
// split on the whitespace padding.
const parts = parseContent(hasEdgeWhitespace ? middle : stringValue);