|
- import json
- from pathlib import Path
- from slugify import slugify
-
- def load_json_file(file_path: str):
- """Load and parse a JSON file"""
- try:
- with open(file_path, 'r', encoding='utf-8') as f:
- return json.load(f)
- except (FileNotFoundError, json.JSONDecodeError) as e:
- print(f"Error reading {file_path}: {str(e)}")
- return {}
-
- def save_json_file(data, file_path: str):
- """Save data to a JSON file"""
- try:
- with open(file_path, 'w', encoding='utf-8') as f:
- json.dump(data, f, indent=2, ensure_ascii=False)
- print(f"Successfully saved: {file_path}")
- except Exception as e:
- print(f"Error saving {file_path}: {str(e)}")
-
- def generate_layout_slug(layout_years: str) -> str:
- return layout_years
-
- def add_slugs_to_data(data):
- """Recursively add slugs to the circuit data structure"""
- new_data = {}
-
- for country, country_data in data.items():
- country_slug = slugify(country)
- new_country_data = {
- "slug": country_slug,
- "cities": {}
- }
-
- for city, city_data in country_data.items():
- city_slug = slugify(city)
- new_city_data = {
- "slug": city_slug,
- "circuits": {}
- }
-
- for circuit_name, circuit_data in city_data.items():
- circuit_slug = slugify(circuit_name)
-
- # Copy all existing circuit data
- new_circuit_data = circuit_data.copy()
- # Add circuit slug
- new_circuit_data["slug"] = circuit_slug
-
- # Add slugs to layouts
- if "layouts" in new_circuit_data:
- new_layouts = {}
- for layout_years, layout_data in new_circuit_data["layouts"].items():
- # Create new layout data with slug
- new_layout_data = layout_data.copy()
- new_layout_data["slug"] = generate_layout_slug(layout_years)
- new_layout_data["years"] = layout_years # Store original years string
-
- new_layouts[layout_years] = new_layout_data
-
- new_circuit_data["layouts"] = new_layouts
-
- new_city_data["circuits"][circuit_name] = new_circuit_data
-
- new_country_data["cities"][city] = new_city_data
-
- new_data[country] = new_country_data
-
- return new_data
-
- def main():
- # Define file paths
- input_file = Path("circuits.json")
- output_file = Path("circuits-with-slugs.json")
-
- # Load existing data
- print(f"Loading data from {input_file}")
- data = load_json_file(input_file)
-
- if not data:
- print("No data loaded. Exiting.")
- return
-
- # Add slugs to the data structure
- print("Adding slugs to data structure...")
- new_data = add_slugs_to_data(data)
-
- # Save the modified data
- print(f"Saving modified data to {output_file}")
- save_json_file(new_data, output_file)
-
- print("Done!")
-
- if __name__ == "__main__":
- main()
|