|
- import json
-
- def update_keys_with_slugs(data):
- if not isinstance(data, dict):
- return data
-
- new_dict = {}
- for key, value in data.items():
- if isinstance(value, dict):
- # Store original key as name if it's not already present
- if 'name' not in value:
- value['name'] = key
-
- # Get the slug and remove it from the value dict
- slug = value.pop('slug', key)
-
- # Recursively process nested dictionaries
- processed_value = update_keys_with_slugs(value)
-
- # Use the slug as the new key
- new_dict[slug] = processed_value
- else:
- new_dict[key] = value
-
- return new_dict
-
- def main():
- try:
- # Read the JSON file with UTF-8 encoding
- with open('./circuits.json', 'r', encoding='utf-8') as file:
- data = json.load(file)
-
- # Process the data
- updated_data = update_keys_with_slugs(data)
-
- # Write the updated data back to the file with UTF-8 encoding and ensure_ascii=False
- with open('./circuits-new.json', 'w', encoding='utf-8') as file:
- json.dump(updated_data, file, indent=2, ensure_ascii=False)
-
- print("Successfully updated circuit keys with slugs")
-
- except FileNotFoundError:
- print("Error: circuits.json file not found")
- except json.JSONDecodeError:
- print("Error: Invalid JSON format in circuits.json")
- except Exception as e:
- print(f"An error occurred: {str(e)}")
-
- if __name__ == "__main__":
- main()
|