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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: show JSON objects in cell using raw data (#4219)
Hoi Dmytroda3cb00f7160
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.mdindex 28487b5262..87fcd902ad 100644--- a/docs/api/layouts/index.md+++ b/docs/api/layouts/index.md@@ -24,6 +24,7 @@ them but just render their children in a certain way.| [`marimo.stat`][marimo.stat] | Display statistics || [`marimo.sidebar`][marimo.sidebar] | Create sidebars || [`marimo.tree`][marimo.tree] | Create tree structures |+| [`marimo.json`][marimo.json] | Create JSON structures || [`marimo.vstack`][marimo.vstack] | Stack elements vertically |## Statefuldiff --git a/docs/api/layouts/json.md b/docs/api/layouts/json.mdnew file mode 100644index 0000000000..eebb66077c--- /dev/null+++ b/docs/api/layouts/json.md@@ -0,0 +1,17 @@+# Json++/// marimo-embed++```python+def __():+ mo.json(+ '["entry", "another entry", {"key": [0, 1, 2]}]',+ label="A JSON in tree..",+ )+ return+```++///++::: marimo.jsondiff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsxindex 65e58f9749..1e48c8d70a 100644--- a/frontend/src/components/editor/output/JsonOutput.tsx+++ b/frontend/src/components/editor/output/JsonOutput.tsx@@ -7,6 +7,7 @@ import {booleanType,defineDataType,intType,+ floatType,nullType,objectType,stringType,@@ -37,6 +38,11 @@ interface Props {name?: string | false;className?: string;++ /**+ * The value types to use for the JSON viewer.+ */+ valueTypes?: "json" | "python";}// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -50,7 +56,7 @@ const CopyButton: React.FC<DataItemProps<any>> = ({ value }) => {const handleCopy = async (evt: React.MouseEvent) => {evt.stopPropagation();- await copyToClipboard(getCopyValue(value));+ await copyToClipboard(value);setCopied(true);setTimeout(() => setCopied(false), 1000);};@@ -76,16 +82,38 @@ const CopyButton: React.FC<DataItemProps<any>> = ({ value }) => {);};+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const JSONCopyButton: React.FC<DataItemProps<any>> = (props) => {+ // if+ return <CopyButton {...props} value={JSON.stringify(props.value, null, 2)} />;+};++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const PyCopyButton: React.FC<DataItemProps<any>> = (props) => {+ return <CopyButton {...props} value={getCopyValue(props.value)} />;+};+/*** Output component for JSON data.*/export const JsonOutput: React.FC<Props> = memo(- ({ data, format = "auto", name = false, className }) => {+ ({+ data,+ format = "auto",+ name = false,+ valueTypes = "python",+ className,+ }) => {const { theme } = useTheme();if (format === "auto") {format = inferBestFormat(data);}+ const valueTypesMap: Record<string, typeof PYTHON_VALUE_TYPES> = {+ python: PYTHON_VALUE_TYPES,+ json: JSON_VALUE_TYPES,+ };+switch (format) {case "tree":return (@@ -99,7 +127,8 @@ export const JsonOutput: React.FC<Props> = memo(backgroundColor: "transparent",}}collapseStringsAfterLength={COLLAPSED_TEXT_LENGTH}- valueTypes={VALUE_TYPE}+ // leave the default valueTypes as it was - 'python', only 'json' is changed+ valueTypes={valueTypesMap[valueTypes]}// disable array grouping (it's misleading) by using a large valuegroupArraysAfterLength={1_000_000}// Built-in clipboard shifts content on hover@@ -173,27 +202,38 @@ const LEAF_RENDERERS = {const MIME_TYPES: Array<DataType<any>> = Object.entries(LEAF_RENDERERS).map(([leafType, render]) => ({is: (value) => typeof value === "string" && value.startsWith(leafType),- PostComponent: CopyButton,+ PostComponent: PyCopyButton,Component: (props) => renderLeaf(props.value, render),}),);const PYTHON_BOOLEAN_TYPE = defineDataType<boolean>({...booleanType,- PostComponent: CopyButton,+ PostComponent: PyCopyButton,Component: ({ value }) => <span>{value ? "True" : "False"}</span>,});const PYTHON_NONE_TYPE = defineDataType<null>({...nullType,- PostComponent: CopyButton,+ PostComponent: PyCopyButton,Component: () => <span>None</span>,});+const JSON_BOOLEAN_TYPE = defineDataType<boolean>({+ ...booleanType,+ PostComponent: JSONCopyButton,+});++const JSON_NONE_TYPE = defineDataType<null>({+ ...nullType,+ PostComponent: JSONCopyButton,+ Component: () => <span>null</span>,+});+const URL_TYPE = defineDataType<string>({...stringType,is: (value) => isUrl(value),- PostComponent: CopyButton,+ PostComponent: PyCopyButton,Component: ({ value }) => (<ahref={value}@@ -208,12 +248,17 @@ const URL_TYPE = defineDataType<string>({const INTEGER_TYPE = defineDataType<number>({...intType,- PostComponent: CopyButton,+ PostComponent: JSONCopyButton,+});++const FLOAT_TYPE = defineDataType<number>({+ ...floatType,+ PostComponent: JSONCopyButton,});const FALLBACK_RENDERER = defineDataType<string>({...stringType,- PostComponent: CopyButton,+ PostComponent: PyCopyButton,});const OBJECT_TYPE = defineDataType<object>({@@ -221,12 +266,27 @@ const OBJECT_TYPE = defineDataType<object>({PreComponent: (props) => (<>{objectType.PreComponent && <objectType.PreComponent {...props} />}- <CopyButton {...props} />+ <PyCopyButton {...props} />+ </>+ ),+});++const JSON_OBJECT_TYPE = defineDataType<object>({+ ...objectType,+ PreComponent: (props) => (+ <>+ {objectType.PreComponent && <objectType.PreComponent {...props} />}+ <JSONCopyButton {...props} /></>),});-const VALUE_TYPE = [+const JSON_FALLBACK_RENDERER = defineDataType<string>({+ ...stringType,+ PostComponent: JSONCopyButton,+});++const PYTHON_VALUE_TYPES = [INTEGER_TYPE,PYTHON_BOOLEAN_TYPE,PYTHON_NONE_TYPE,@@ -237,6 +297,15 @@ const VALUE_TYPE = [].reverse();// Last one wins, so we reverse the array.+const JSON_VALUE_TYPES = [+ INTEGER_TYPE,+ FLOAT_TYPE,+ JSON_BOOLEAN_TYPE,+ JSON_NONE_TYPE,+ JSON_OBJECT_TYPE,+ JSON_FALLBACK_RENDERER,+].reverse();+function leafData(leaf: string): string {const delimIndex = leaf.indexOf(":");if (delimIndex === -1) {diff --git a/frontend/src/plugins/layout/JsonOutputPlugin.tsx b/frontend/src/plugins/layout/JsonOutputPlugin.tsxindex a85029c869..15361338d8 100644--- a/frontend/src/plugins/layout/JsonOutputPlugin.tsx+++ b/frontend/src/plugins/layout/JsonOutputPlugin.tsx@@ -14,6 +14,10 @@ interface Data {* The JSON data to display*/jsonData?: unknown;+ /**+ * The format of the JSON data. Can be 'auto', 'json', or 'yaml'.+ */+ valueTypes?: "json" | "python";}export class JsonOutputPlugin implements IStatelessPlugin<Data> {@@ -22,6 +26,7 @@ export class JsonOutputPlugin implements IStatelessPlugin<Data> {validator = z.object({name: z.string().nullish(),jsonData: z.unknown(),+ valueTypes: z.enum(["json", "python"]).default("python"),});render({ data, host }: IStatelessPluginProps<Data>): JSX.Element {@@ -29,7 +34,12 @@ export class JsonOutputPlugin implements IStatelessPlugin<Data> {const name = data.name === undefined ? false : data.name || "";return (<EmotionCacheProvider container={host.shadowRoot}>- <JsonOutput data={data.jsonData} format="auto" name={name} />+ <JsonOutput+ data={data.jsonData}+ format="auto"+ valueTypes={data.valueTypes}+ name={name}+ /></EmotionCacheProvider>);}diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 9f7e460e3c..02a89de9cb 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -78,6 +78,7 @@ __all__ = ["style","tabs","tree",+ "json","video","vstack",]@@ -104,6 +105,7 @@ from marimo._plugins.stateless.download import downloadfrom marimo._plugins.stateless.flex import hstack, vstackfrom marimo._plugins.stateless.icon import iconfrom marimo._plugins.stateless.image import image+from marimo._plugins.stateless.json_component import jsonfrom marimo._plugins.stateless.lazy import lazyfrom marimo._plugins.stateless.mermaid import mermaidfrom marimo._plugins.stateless.nav_menu import nav_menudiff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.pyindex c49bbe1313..56dd2c4899 100644--- a/marimo/_output/formatters/structures.py+++ b/marimo/_output/formatters/structures.py@@ -13,7 +13,9 @@ from marimo._plugins.stateless import plain_textfrom marimo._utils.flatten import CyclicStructureError, flatten-def _leaf_formatter(value: object) -> bool | None | str | int:+def _leaf_formatter(+ value: object,+) -> bool | None | str | int:formatter = formatting.get_formatter(value)if formatter is not None:return ":".join(formatter(value))diff --git a/marimo/_plugins/stateless/json_component.py b/marimo/_plugins/stateless/json_component.pynew file mode 100644index 0000000000..7aeb93342e--- /dev/null+++ b/marimo/_plugins/stateless/json_component.py@@ -0,0 +1,53 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++from json import loads+from typing import Any, Optional++from marimo._output.hypertext import Html+from marimo._output.rich_help import mddoc+from marimo._plugins.stateless import json_output+++@mddoc+def json(+ data: str | dict[str, Any] | list[Any],+ label: Optional[str] = None,+) -> Html:+ """Render a JSON with tree.++ Example:+ ```python3+ mo.json(+ '["entry", "another entry", {"key": [0, 1, 2]}]',+ label="A JSON in tree.",+ )+ ```++ Args:+ data: JSON string or JSON-compatible Python object(s) to render+ label: optional text label for the tree++ Returns:+ Html: `Html` object+ """+ if not isinstance(data, (str, dict, list)):+ raise ValueError(+ "Argument `data` must be a str, dict, or list, "+ f"but got: {type(data)}"+ )++ if isinstance(data, str):+ try:+ data = loads(data)+ except ValueError as e:+ raise ValueError(+ "Argument `data` must be a valid JSON string, "+ + f"but got: {data}"+ ) from e++ return json_output.json_output(+ json_data=data,+ name=label,+ value_types="json",+ )diff --git a/marimo/_plugins/stateless/json_output.py b/marimo/_plugins/stateless/json_output.pyindex 1da2fc4a3d..4820b9c793 100644--- a/marimo/_plugins/stateless/json_output.py+++ b/marimo/_plugins/stateless/json_output.py@@ -1,31 +1,41 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Optional+from typing import Literal, Optionalfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import JSONType, build_stateless_plugin-def json_output(json_data: JSONType, name: Optional[str] = None) -> Html:+def json_output(+ json_data: JSONType,+ name: Optional[str] = None,+ *,+ value_types: Literal["python", "json"] = "python",+) -> Html:"""Build a json output element.Args:-----json_data: JSON-serializable data to displayname: optional text label+ value_types: optional value types to display,+ e.g. "python" (default) or "json"Returns:--------A string of HTML for a JSON output element."""+ element_args = {+ "json-data": json_data,+ "value-types": value_types,+ }+ if name is not None:+ element_args["name"] = name+return Html(build_stateless_plugin(component_name="marimo-json-output",- args=(- {"json-data": json_data, "name": name}- if name is not None- else {"json-data": json_data}- ),+ args=element_args,))diff --git a/marimo/_plugins/stateless/tree.py b/marimo/_plugins/stateless/tree.pyindex 276413e17a..78734a84c8 100644--- a/marimo/_plugins/stateless/tree.py+++ b/marimo/_plugins/stateless/tree.py@@ -43,4 +43,8 @@ def tree(json_data = format_structure(items)except CyclicStructureError:json_data = str(items)- return json_output.json_output(json_data=json_data, name=label)+ return json_output.json_output(+ json_data=json_data,+ name=label,+ value_types="python",+ )diff --git a/mkdocs.yml b/mkdocs.ymlindex cbaa78f25b..bd6d67d646 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -190,6 +190,7 @@ nav:- Accordion: api/layouts/accordion.md- Callout: api/layouts/callout.md- Carousel: api/layouts/carousel.md+ - Json: api/layouts/json.md- Justify: api/layouts/justify.md- Lazy: api/layouts/lazy.md- Plain: api/layouts/plain.mddiff --git a/tests/_islands/snapshots/island-mimetypes.txt b/tests/_islands/snapshots/island-mimetypes.txtindex 9198403681..3c08203e59 100644--- a/tests/_islands/snapshots/island-mimetypes.txt+++ b/tests/_islands/snapshots/island-mimetypes.txt@@ -24,7 +24,7 @@data-reactive="true"><marimo-cell-output>- <marimo-json-output data-json-data='{"key": "value"}'></marimo-json-output>+ <marimo-json-output data-json-data='{"key": "value"}' data-value-types='"python"'></marimo-json-output></marimo-cell-output><marimo-cell-code hidden>%7B'key'%3A%20'value'%7D</marimo-cell-code></marimo-island>@@ -34,7 +34,7 @@data-reactive="true"><marimo-cell-output>- <marimo-json-output data-json-data='[1, "text/html:<span class=\"markdown prose dark:prose-invert\"><span class=\"paragraph\">Hello</span></span>"]'></marimo-json-output>+ <marimo-json-output data-json-data='[1, "text/html:<span class=\"markdown prose dark:prose-invert\"><span class=\"paragraph\">Hello</span></span>"]' data-value-types='"python"'></marimo-json-output></marimo-cell-output><marimo-cell-code hidden>%5B1%2C%20mo.md('Hello')%5D</marimo-cell-code></marimo-island>\ No newline at end of filediff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex 31b5951d44..3b32214754 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -35,6 +35,7 @@ imageislandsMarimoIslandGeneratorMarimoIslandStub+jsonlatexlazyleft