# Author: Jeff R. Robbins with assistance from MAI-Code-1-Flash via GitHub Copilot. # Email: jr@QlikPerf.com # Purpose: Convert the JSON output from ctrl-q.exe to CSV format for easier analysis in Excel or other tools. # Dependencies: Python 3.x, Qlik Sense Desktop or Server, and the ctrl-q.exe utility from https://github.com/ptarmiganlabs/ctrl-q import csv import json # Define file paths json_file_path = "output.ctrl-q.txt" csv_file_path = "output.csv" # Detect the source text encoding from the BOM and then open the file accordingly. def detect_json_encoding(file_path): with open(file_path, "rb") as raw_file: header = raw_file.read(4) if header.startswith(b"\xff\xfe") or header.startswith(b"\xfe\xff"): return "utf-16" if header.startswith(b"\xef\xbb\xbf"): return "utf-8-sig" return "utf-8" # 1. Load the JSON data from the payload portion of the file. def load_json_payload(file_path): encoding = detect_json_encoding(file_path) with open(file_path, "r", encoding=encoding) as json_file: raw_text = json_file.read() lines = raw_text.splitlines() marker = "Sessions data in JSON format" payload_lines = lines for i, line in enumerate(lines): if marker in line: payload_lines = lines[i + 1:] break payload = "\n".join(payload_lines).strip() if not payload: return None return json.loads(payload) # Parse the JSON payload after removing any non-JSON preamble. data = load_json_payload(json_file_path) # Exclude system/admin records from CSV export: if isinstance(data, list): data = [record for record in data if isinstance(record, dict) and record.get("userId") != "sv_qlikadmin"] # 2. Open the CSV file for writing with open(csv_file_path, "w", newline="", encoding="utf-8") as csv_file: # Check if data is a list and has at least one item if isinstance(data, list) and len(data) > 0: # Extract headers from the keys of the first dictionary headers = data[0].keys() # Create a DictWriter object writer = csv.DictWriter(csv_file, fieldnames=headers) # Write headers and all data rows writer.writeheader() writer.writerows(data) else: print("JSON structure is not a list of objects or no rows remain after filtering.")