File size: 1,820 Bytes
a55ea57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
File: /data.py
Created Date: Friday October 24th 2025
Author: Christian Nonis <alch.infoemail@gmail.com>
-----
Last Modified: Thursday February 19th 2026 7:45:12 pm
Modified By: Christian Nonis <alch.infoemail@gmail.com>
-----
"""

import json
import re
from typing import Any
import uuid


def str_to_json(text: str | None, empty_fallback: bool = False) -> list[str]:
    """
    Convert a string to a json list of strings.
    """
    if not text:
        return []
    text = text.strip().replace("```json", "").replace("```", "")
    try:
        return json.loads(text)
    except Exception:
        try:
            arr_match = re.search(r"\[.*\]", text, flags=re.DOTALL)
            if arr_match:
                json_text = arr_match.group(0)
            else:
                obj_match = re.search(r"\{.*\}", text, flags=re.DOTALL)
                if obj_match:
                    json_text = obj_match.group(0)
                else:
                    json_text = text
            return json.loads(json_text)
        except Exception:
            if empty_fallback:
                return []
            raise Exception(f"Invalid JSON string: {text}")


def always_dict(obj: Any) -> dict:
    """
    Convert a string or object to a dict.
    """
    if not obj:
        return {}
    if isinstance(obj, dict):
        return obj
    if isinstance(obj, str):
        try:
            return json.loads(obj)
        except Exception:
            try:
                return json.loads(obj)
            except Exception:
                print(f"Invalid JSON string: {obj}")
                return {}
    return {}

def is_uuid(text: str) -> bool:
    """
    Check if a string is a valid UUID.
    """
    try:
        uuid.UUID(text.strip())
        return True
    except Exception:
        return False