import json import sys def extract_hosts_to_file(json_data, output_filename="hosts.txt"): """Extracts hosts from a JSON object and writes them to a file. Args: json_data: The JSON object containing the hosts. output_filename: The name of the output text file (default: hosts.txt). """ try: with open(output_filename, 'w') as outfile: for host in json_data.get("hosts", []): outfile.write(host.strip() + '\n') except (IOError, json.JSONDecodeError) as e: print(f"An error occurred: {e}") if __name__ == "__main__": if len(sys.argv) > 1: json_filename = sys.argv[1] try: with open(json_filename, 'r') as f: json_data = json.load(f) except FileNotFoundError: print(f"Error: File '{json_filename}' not found.") sys.exit(1) except json.JSONDecodeError: print(f"Error: Invalid JSON format in '{json_filename}'.") sys.exit(1) if len(sys.argv) > 2: output_filename = sys.argv[2] extract_hosts_to_file(json_data, output_filename) print(f"Hosts extracted to '{output_filename}'") else: extract_hosts_to_file(json_data) print("Hosts extracted to 'hosts.txt'") else: print("Usage: python script_name.py (optional)") default_json = {"hosts": []} extract_hosts_to_file(default_json) print("Hosts (from default JSON) extracted to 'hosts.txt'")