{"record":{"id":"6c92b8a8f6cf66dc","repo":"OpenBB-finance/OpenBB","slug":"failed-to-convert-chart-to-json","errorCode":null,"errorMessage":"Failed to convert chart to JSON","messagePattern":"Failed to convert chart to JSON","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"openbb_platform/extensions/platform_api/openbb_platform_api/response_models.py","lineNumber":239,"sourceCode":"            )\n\n        # If parameter was supplied, assume the data is formatted correctly.\n        if content and parse_as:\n            data_format = {\n                \"data_type\": \"object\",\n                \"parse_as\": parse_as,\n            }\n            values.data_format = data_format\n            del values.parse_as\n\n            return values\n\n        if content.__class__.__name__ == \"Figure\":\n            values.parse_as = \"chart\"\n            try:\n                content = content.to_json()\n            except Exception as e:\n                raise ValueError(\"Failed to convert chart to JSON\") from e\n            values.content = content\n        elif isinstance(content, dict) and \"layout\" in content and \"data\" in content:\n            values.parse_as = \"chart\"\n        elif isinstance(content, list) and all(\n            isinstance(item, dict) for item in content\n        ):\n            values.parse_as = \"table\"\n        elif isinstance(content, pd.DataFrame):\n            values.parse_as = \"table\"\n            try:\n                content = json.loads(content.to_json(orient=\"records\"))\n            except Exception as e:\n                raise ValueError(\"Failed to convert DataFrame to JSON\") from e\n            values.content = content\n        elif isinstance(content, dict) and all(\n            isinstance(v, list) for v in content.values()\n        ):\n            values.parse_as = \"table\"","sourceCodeStart":221,"sourceCodeEnd":257,"githubUrl":"https://github.com/OpenBB-finance/OpenBB/blob/3e071fcc2cd9f891cac6040ae60296dba76dab46/openbb_platform/extensions/platform_api/openbb_platform_api/response_models.py#L221-L257","documentation":"Thrown by the OmniWidgetResponseModel Pydantic model_validator when the content is detected as a plotly Figure (duck-typed by class name) but calling Figure.to_json() raises. The widget response pipeline serializes charts to JSON for the frontend; any exception during plotly serialization is wrapped in this ValueError.","triggerScenarios":"Constructing OmniWidgetResponseModel(content=<plotly Figure object>) where the Figure contains objects plotly cannot serialize (e.g. custom dtypes, NaN-heavy data, non-JSON-serializable custom trace attributes, or a numpy array inside hovertemplate data), or where 'Figure' is a different class that also has a failing to_json().","commonSituations":"Passing a matplotlib figure (also named Figure) instead of a plotly one; a Figure built from a DataFrame with Timestamp/TimestampTZ indices or Decimal values that plotly's JSON encoder rejects; plotly version changes that alter to_json behavior.","solutions":["Verify the object is a plotly.graph_objs.Figure (or plotly FigureWidget), not a matplotlib.figure.Figure.","Test fig.to_json() standalone in a REPL to surface the underlying exception chained via __cause__.","Pre-convert the Figure yourself with json.loads(fig.to_json()) and pass the resulting dict, or pass parse_as='chart' with the already-serialized dict {'data':..., 'layout':...}.","Sanitize the Figure before passing it: cast Timestamp indices to strings and replace non-serializable values."],"exampleFix":"# before\nresp = OmniWidgetResponseModel(content=matplotlib_fig)  # wrong Figure class\n\n# after\nimport plotly.graph_objects as go\nfig = go.Figure(...)  # plotly Figure\nresp = OmniWidgetResponseModel(content=fig)","handlingStrategy":"validation","validationCode":"from plotly.graph_objs import Figure\nif not isinstance(content, Figure):\n    raise TypeError(\"content must be a plotly Figure, dict, or list of records\")\ncontent = json.loads(content.to_json())  # fail early, before the model validator","typeGuard":"def is_plotly_figure(obj) -> bool:\n    return obj.__class__.__name__ == \"Figure\" and hasattr(obj, \"to_json\")","tryCatchPattern":"try:\n    resp = OmniWidgetResponseModel(content=fig)\nexcept ValueError as e:\n    if \"chart to JSON\" in str(e) and e.__cause__:\n        logger.error(\"plotly serialization failed: %s\", e.__cause__)\n    raise","preventionTips":["Pass plotly figures only, never matplotlib","Pre-serialize with fig.to_json() in tests to catch encoding problems","Inspect __cause__ on the wrapped ValueError for the root error"],"tags":["plotly","serialization","pydantic","widget"],"backgroundTag":null,"analyzedSha":"3e071fcc2cd9f891cac6040ae60296dba76dab46","analyzedAt":"2026-08-14T23:40:48.960Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}