Convert a figure to JSON and write it to a file or writeable object. Note: A figure converted to JSON with one version of Plotly.py may not be compatible with another version. Parameters ---------- fig: Figure object or dict representing a figure file: str or
(fig, file, validate=True, pretty=False, remove_uids=True, engine=None)
| 223 | |
| 224 | |
| 225 | def write_json(fig, file, validate=True, pretty=False, remove_uids=True, engine=None): |
| 226 | """ |
| 227 | Convert a figure to JSON and write it to a file or writeable |
| 228 | object. |
| 229 | |
| 230 | Note: A figure converted to JSON with one version of Plotly.py may not be compatible with another version. |
| 231 | |
| 232 | Parameters |
| 233 | ---------- |
| 234 | fig: |
| 235 | Figure object or dict representing a figure |
| 236 | |
| 237 | file: str or writeable |
| 238 | A string representing a local file path or a writeable object |
| 239 | (e.g. a pathlib.Path object or an open file descriptor) |
| 240 | |
| 241 | pretty: bool (default False) |
| 242 | True if JSON representation should be pretty-printed, False if |
| 243 | representation should be as compact as possible. |
| 244 | |
| 245 | remove_uids: bool (default True) |
| 246 | True if trace UIDs should be omitted from the JSON representation |
| 247 | |
| 248 | engine: str (default None) |
| 249 | The JSON encoding engine to use. One of: |
| 250 | - "json" for an engine based on the built-in Python json module |
| 251 | - "orjson" for a faster engine that requires the orjson package |
| 252 | - "auto" for the "orjson" engine if available, otherwise "json" |
| 253 | If not specified, the default engine is set to the current value of |
| 254 | plotly.io.json.config.default_engine. |
| 255 | Returns |
| 256 | ------- |
| 257 | None |
| 258 | """ |
| 259 | |
| 260 | # Get JSON string |
| 261 | # --------------- |
| 262 | # Pass through validate argument and let to_json handle validation logic |
| 263 | json_str = to_json( |
| 264 | fig, validate=validate, pretty=pretty, remove_uids=remove_uids, engine=engine |
| 265 | ) |
| 266 | |
| 267 | # Try to cast `file` as a pathlib object `path`. |
| 268 | # ---------------------------------------------- |
| 269 | if isinstance(file, str): |
| 270 | # Use the standard Path constructor to make a pathlib object. |
| 271 | path = Path(file) |
| 272 | elif isinstance(file, Path): |
| 273 | # `file` is already a Path object. |
| 274 | path = file |
| 275 | else: |
| 276 | # We could not make a Path object out of file. Either `file` is an open file |
| 277 | # descriptor with a `write()` method or it's an invalid object. |
| 278 | path = None |
| 279 | |
| 280 | # Open file |
| 281 | # --------- |
| 282 | if path is None: |