85 lines
2.7 KiB
Python
85 lines
2.7 KiB
Python
import json
|
|
import re
|
|
import sys
|
|
|
|
def read_mapping(mapping_file):
|
|
"""
|
|
Read device-to-IP mapping from a text file.
|
|
Format: <device_name> <IP_address>
|
|
Returns a dictionary with DPM{number}_DEVICE and DPM{number}_TEXT mappings.
|
|
"""
|
|
mapping = {}
|
|
try:
|
|
with open(mapping_file, 'r') as f:
|
|
for i, line in enumerate(f, 1):
|
|
line = line.strip()
|
|
if not line or line.startswith('#'):
|
|
continue
|
|
try:
|
|
device, ip = line.split()
|
|
mapping[f"DPM{i}_DEVICE"] = device
|
|
mapping[f"DPM{i}_TEXT"] = f"{device} {ip}"
|
|
except ValueError:
|
|
print(f"Warning: Skipping invalid line {i} in {mapping_file}: '{line}'")
|
|
return mapping
|
|
except FileNotFoundError:
|
|
print(f"Error: Mapping file {mapping_file} not found.")
|
|
sys.exit(1)
|
|
except Exception as e:
|
|
print(f"Error reading mapping file: {str(e)}")
|
|
sys.exit(1)
|
|
|
|
def replace_placeholders(data, mapping):
|
|
"""
|
|
Recursively replace placeholders in the data structure with values from mapping.
|
|
"""
|
|
if isinstance(data, dict):
|
|
return {k: replace_placeholders(v, mapping) for k, v in data.items()}
|
|
elif isinstance(data, list):
|
|
return [replace_placeholders(item, mapping) for item in data]
|
|
elif isinstance(data, str):
|
|
for placeholder, value in mapping.items():
|
|
data = re.sub(r'\b' + re.escape(placeholder) + r'\b', value, data)
|
|
return data
|
|
else:
|
|
return data
|
|
|
|
def process_view_json(input_file, output_file, mapping):
|
|
"""
|
|
Process view.json, replace placeholders, and save to output_file.
|
|
"""
|
|
try:
|
|
with open(input_file, 'r') as f:
|
|
data = json.load(f)
|
|
|
|
modified_data = replace_placeholders(data, mapping)
|
|
|
|
with open(output_file, 'w') as f:
|
|
json.dump(modified_data, f, indent=4)
|
|
|
|
print(f"Successfully processed {input_file} and saved to {output_file}")
|
|
|
|
except FileNotFoundError:
|
|
print(f"Error: The file {input_file} was not found.")
|
|
sys.exit(1)
|
|
except json.JSONDecodeError:
|
|
print(f"Error: The file {input_file} is not a valid JSON file.")
|
|
sys.exit(1)
|
|
except Exception as e:
|
|
print(f"An error occurred: {str(e)}")
|
|
sys.exit(1)
|
|
|
|
def main():
|
|
if len(sys.argv) != 3:
|
|
print("Usage: python replace_placeholders.py <mapping_file> <view_json_file>")
|
|
sys.exit(1)
|
|
|
|
mapping_file = sys.argv[1]
|
|
input_json_file = sys.argv[2]
|
|
output_json_file = "view.json"
|
|
|
|
mapping = read_mapping(mapping_file)
|
|
process_view_json(input_json_file, output_json_file, mapping)
|
|
|
|
if __name__ == "__main__":
|
|
main() |