import json

def preprocess_json_content(content):
    # Attempt to find the main JSON object and remove any extra data
    stack = []
    end_index = 0

    for i, char in enumerate(content):
        if char == '{' or char == '[':
            stack.append(char)
        elif char == '}' or char == ']':
            if stack:
                stack.pop()
            if not stack:  # Found the end of the main JSON object
                end_index = i
                break

    if end_index > 0:
        # Return only the main JSON object
        return content[:end_index + 1]
    else:
        # If no valid JSON object found, return the original content
        return content

def correct_json_file_format(file_path):
    try:
        # Read the file content with UTF-8 encoding
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        # Preprocess the content to isolate the main JSON object
        processed_content = preprocess_json_content(content)

        # Attempt to parse the processed JSON content
        json_data = json.loads(processed_content)

        # If parsing is successful, re-write the JSON file with proper formatting
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(json_data, file, indent=4, ensure_ascii=False)

        print("The JSON file has been validated and corrected.")
        return True
    except json.JSONDecodeError as e:
        print(f"The JSON file is invalid: {e}")
        return False
    except FileNotFoundError:
        print(f"The file {file_path} does not exist.")
        return False
    except Exception as e:
        print(f"An error occurred: {e}")
        return False

file_path = 'license.json'
correct_json_file_format(file_path)
