Skip to content

Instantly share code, notes, and snippets.

@enakai00
Created March 14, 2026 10:07
Show Gist options
  • Select an option

  • Save enakai00/206d4c9af198c5d12814fb66e2eca735 to your computer and use it in GitHub Desktop.

Select an option

Save enakai00/206d4c9af198c5d12814fb66e2eca735 to your computer and use it in GitHub Desktop.
fix_widget_metadata.py
import json
import os
def add_widget_state(notebook_path, output_path=None):
"""
Adds "state": {} to each widget definition under metadata.widgets
in a Jupyter Notebook file.
"""
# If no output path is provided, overwrite the original file
if output_path is None:
output_path = notebook_path
if not os.path.exists(notebook_path):
print(f"Error: File '{notebook_path}' not found.")
return
# 1. Load the notebook JSON
with open(notebook_path, 'r', encoding='utf-8') as f:
notebook = json.load(f)
modified = False
# 2. Safely navigate the JSON structure
metadata = notebook.get('metadata', {})
widgets = metadata.get('widgets', {})
if widgets:
# 3. Iterate through widget MIME types (like "application/vnd.jupyter.widget-state+json")
for widget_key, widget_data in widgets.items():
if isinstance(widget_data, dict):
# Add or overwrite the "state" key
widget_data['state'] = {}
modified = True
print(f"Added 'state': {{}} to '{widget_key}'")
# 4. Save the modified notebook
if modified:
with open(output_path, 'w', encoding='utf-8') as f:
# indent=2 matches standard Jupyter Notebook formatting (as seen in your screenshot)
json.dump(notebook, f, indent=2)
print(f"Successfully updated '{output_path}'.")
else:
print("No widgets found in metadata. No changes made.")
filename = 'yourfile.ipynb'
add_widget_state(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment