import json # === Map this from previous step (the raw JSON response) === raw_data = """{{paste the full raw JSON here or map the field}}""" report_month = "Mar 2026" # You can also do: data["Report"]["ReportMonth"] later # ==================== ROBUST CLEANING ==================== # 1. Extract the JSON object safely start = raw_data.find("{") end = raw_data.rfind("}") + 1 cleaned = raw_data[start:end] # 2. Strong cleaning for Pabbly + Unicode issues cleaned = cleaned.replace("\\n", " ") # replace literal \n cleaned = cleaned.replace("\n", " ") # replace actual newlines cleaned = cleaned.replace("\\\"", '"') # fix escaped quotes cleaned = cleaned.replace('\\"', '"') cleaned = " ".join(cleaned.split()) # normalize all whitespace # 3. Parse JSON try: data = json.loads(cleaned) except Exception as e: # Extra fallback with strict=False try: data = json.loads(cleaned, strict=False) except Exception as e2: raise Exception(f"JSON parsing failed: {str(e2)}") # ==================== PROCESS STUDENTS ==================== students = data.get("Students", []) if not students: raise Exception("No students found in data") # Build result result = {key: [] for key in students[0].keys()} for student in students: for key in result: value = student.get(key, "") result[key].append(str(value).strip()) # Add MonthReport column result["MonthReport"] = [report_month] * len(students) # Convert lists to comma-separated strings (exact format you want) for key in result: result[key] = ", ".join(result[key]) # Output print(json.dumps(result, indent=2))