File size: 1,983 Bytes
1ef829e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import json
import re
import ast
from loguru import logger

class JsonProcessor:
    def process_response(self, response):
        try:
            # Search for JSON string in the response
            json_str_match = re.search(r'\{.*\}', response, re.DOTALL)
            if json_str_match:
                # Get the matched JSON string
                json_str = json_str_match.group()
                logger.debug(f"Full JSON string: {json_str}")  

                # Try to parse as Python literal first, then convert to JSON
                try:
                    # First try to evaluate as Python literal
                    python_obj = ast.literal_eval(json_str)
                    # Convert to proper JSON
                    response_json = json.loads(json.dumps(python_obj))
                except (ValueError, SyntaxError):
                    # Fall back to string replacement method
                    # Replace escape characters and remove trailing commas
                    json_str = json_str.replace("\\", "")
                    json_str = json_str.replace(r'\\_', '_')
                    json_str = re.sub(r',\s*}', '}', json_str)
                    json_str = re.sub(r',\s*\]', ']', json_str)
                    
                    # Convert Python format to JSON format
                    json_str = json_str.replace("'", '"')  # Single quotes to double quotes
                    json_str = json_str.replace('None', 'null')  # Python None to JSON null

                    # Parse the JSON string
                    response_json = json.loads(json_str)
                return response_json
            else:
                logger.error("No JSON string match found in response.")
                return None

        except json.JSONDecodeError as e:
            logger.error(f"JSONDecodeError: {e}")
        except Exception as e:
            logger.error(f"Unexpected error: {e}")

        return None