Skip to content

JsonContainerComponent

Модуль для работы с JSON-контейнерами на веб-страницах.

Содержит компонент для чтения и проверки JSON-данных в контейнерах. Использует playwright для взаимодействия с элементами страницы.

JsonContainerComponent

Bases: BaseComponent

Компонент для работы с JSON-данными на странице.

Предоставляет методы чтения и проверки JSON-данных в контейнерах.

Source code in components\json_container_component.py
 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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class JsonContainerComponent(BaseComponent):
    """Компонент для работы с JSON-данными на странице.

    Предоставляет методы чтения и проверки JSON-данных в контейнерах.

    """

    def __init__(self, page: Page) -> None:
        """Инициализирует JSON-контейнер.

        Args:
            page: Экземпляр страницы Playwright.
        """

        super().__init__(page)


    # Действия:
    def format_json_string(self, json_string: str) -> str:
        """Форматирует строку JSON для корректного парсинга.

        Args:
            json_string: Сырая строка с JSON-данными.

        Returns:
            str: Отформатированная строка JSON.
        """

        lines = json_string.splitlines()
        formatted_lines = []
        stack = []  # Стек для отслеживания вложенности
        current_indent = 0

        for line in lines:
            line = line.strip()
            if not line:
                continue

            # Определяем тип текущей строки
            if line in ['{', '[']:
                # Начало объекта или массива
                formatted_lines.append('  ' * current_indent + line)
                stack.append(line)
                current_indent += 1
            elif line in ['}', ']']:
                # Конец объекта или массива
                current_indent -= 1
                if stack and stack[-1] in ['{', '[']:
                    stack.pop()
                formatted_lines.append('  ' * current_indent + line)
            elif re.match(r'^\d+:\{', line):
                # Элемент массива с индексом (0:{, 1:{, etc.)
                # Убираем индекс и оставляем только {
                formatted_lines.append('  ' * current_indent + '{')
                stack.append('{')
                current_indent += 1
            elif ':' in line:
                # Пара ключ:значение
                key, value = line.split(':', 1)
                key = key.strip()
                value = value.strip()

                # Добавляем кавычки к ключу если их нет (включая $)
                if not (key.startswith('"') and key.endswith('"')):
                    key = f'"{key}"'

                # Обработка значений
                if value in ['{', '[']:
                    # Значение - начало объекта или массива
                    formatted_line = f'{key}: {value}'
                    formatted_lines.append('  ' * current_indent + formatted_line)
                    stack.append(value)
                    current_indent += 1
                elif value in ['}', ']']:
                    # Не должно происходить, но на всякий случай
                    current_indent -= 1
                    formatted_line = f'{key}: {value}'
                    formatted_lines.append('  ' * current_indent + formatted_line)
                    if stack:
                        stack.pop()
                else:
                    # Простое значение
                    # Добавляем кавычки к строковым значениям если их нет
                    if (value and
                        not value.isdigit() and
                        not value.replace('.', '', 1).isdigit() and  # Для чисел с точкой
                        value not in ['true', 'false', 'null'] and
                        not value.startswith('"') and not value.endswith('"') and
                        not value.startswith('{') and not value.startswith('[')):
                        value = f'"{value}"'

                    formatted_line = f'{key}: {value}'
                    formatted_lines.append('  ' * current_indent + formatted_line)
            else:
                # Простая строка (скорее всего значение в массиве)
                formatted_lines.append('  ' * current_indent + line)

        # Добавляем запятые где необходимо
        result = []
        for i, current_line in enumerate(formatted_lines):

            # Проверяем, нужно ли добавить запятую
            if i < len(formatted_lines) - 1:
                next_line = formatted_lines[i + 1]

                # Определяем, находимся ли мы внутри массива
                in_array = any(bracket == '[' for bracket in stack)

                # Не добавляем запятую если:
                # - текущая строка это { или [
                # - следующая строка это } или ]
                # - текущая строка уже заканчивается запятой
                # - следующая строка начинается с } или ] (для элементов массива)
                should_add_comma = (
                    not current_line.endswith('{') and
                    not current_line.endswith('[') and
                    not current_line.endswith(',') and
                    not next_line.strip().endswith('}') and
                    not next_line.strip().endswith(']') and
                    not next_line.strip().startswith('}') and
                    not next_line.strip().startswith(']') and
                    not (in_array and next_line.strip() == ']')  # Не добавлять запятую перед закрытием массива
                )

                # Для элементов массива (объектов) добавляем запятую после }
                if (in_array and
                    current_line.strip() == '}' and
                    next_line.strip() != ']' and
                    not next_line.strip().startswith('}')):
                    should_add_comma = True

                if should_add_comma:
                    current_line += ','

            result.append(current_line)

        return '\n'.join(result)

    def read_data(self, locator: Any) -> Dict:
        """Читает и форматирует JSON-данные из указанного локатора.

        Args:
            locator: Локатор элемента с JSON-данными.

        Returns:
            dict: Распарсенный JSON-объект.

        Raises:
            json.JSONDecodeError: Если данные не могут быть преобразованы в JSON.
        """

        # Чтение JSON-содержимого из рабочей области
        loc = self.get_locator(locator)
        json_string = loc.inner_text()

        # Сохранение исходной JSON строки в файл
        with open('json_string.txt', 'w', encoding='utf-8') as f:
            f.write(json_string)
        logger.info("Исходная JSON строка сохранена в файл: json_string.txt")

        formatted_json_string = self.format_json_string(json_string)

        # Сохранение отформатированной JSON строки в файл
        with open('formatted_json_string.txt', 'w', encoding='utf-8') as f:
            f.write(formatted_json_string)
        logger.info("Отформатированная JSON строка сохранена в файл: formatted_json_string.txt")

        try:
            data = json.loads(formatted_json_string)
        except json.JSONDecodeError as e:
            # Дополнительная отладка
            logger.error(f"JSON decode error: {e}")
            logger.error(f"Formatted JSON: {formatted_json_string}")
            assert False, f"Invalid json content. Error: {e}"

        return data

    # Проверки:
    def check_json_equals(self, actual: Any, expected: Any, msg: str) -> None:
        """Сравнивает JSON-объекты на идентичность.

        Args:
            actual: Фактический JSON-объект.
            expected: Ожидаемый JSON-объект.
            msg: Сообщение об ошибке.

        Raises:
            AssertionError: Если объекты не идентичны.
        """

        diff = jsondiff.diff(expected, actual, syntax='symmetric')
        assert len(diff) == 0, f"{msg}. DIFF is {diff}"

__init__(page)

Инициализирует JSON-контейнер.

Parameters:

Name Type Description Default
page Page

Экземпляр страницы Playwright.

required
Source code in components\json_container_component.py
25
26
27
28
29
30
31
32
def __init__(self, page: Page) -> None:
    """Инициализирует JSON-контейнер.

    Args:
        page: Экземпляр страницы Playwright.
    """

    super().__init__(page)

check_json_equals(actual, expected, msg)

Сравнивает JSON-объекты на идентичность.

Parameters:

Name Type Description Default
actual Any

Фактический JSON-объект.

required
expected Any

Ожидаемый JSON-объект.

required
msg str

Сообщение об ошибке.

required

Raises:

Type Description
AssertionError

Если объекты не идентичны.

Source code in components\json_container_component.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def check_json_equals(self, actual: Any, expected: Any, msg: str) -> None:
    """Сравнивает JSON-объекты на идентичность.

    Args:
        actual: Фактический JSON-объект.
        expected: Ожидаемый JSON-объект.
        msg: Сообщение об ошибке.

    Raises:
        AssertionError: Если объекты не идентичны.
    """

    diff = jsondiff.diff(expected, actual, syntax='symmetric')
    assert len(diff) == 0, f"{msg}. DIFF is {diff}"

format_json_string(json_string)

Форматирует строку JSON для корректного парсинга.

Parameters:

Name Type Description Default
json_string str

Сырая строка с JSON-данными.

required

Returns:

Name Type Description
str str

Отформатированная строка JSON.

Source code in components\json_container_component.py
 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
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def format_json_string(self, json_string: str) -> str:
    """Форматирует строку JSON для корректного парсинга.

    Args:
        json_string: Сырая строка с JSON-данными.

    Returns:
        str: Отформатированная строка JSON.
    """

    lines = json_string.splitlines()
    formatted_lines = []
    stack = []  # Стек для отслеживания вложенности
    current_indent = 0

    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Определяем тип текущей строки
        if line in ['{', '[']:
            # Начало объекта или массива
            formatted_lines.append('  ' * current_indent + line)
            stack.append(line)
            current_indent += 1
        elif line in ['}', ']']:
            # Конец объекта или массива
            current_indent -= 1
            if stack and stack[-1] in ['{', '[']:
                stack.pop()
            formatted_lines.append('  ' * current_indent + line)
        elif re.match(r'^\d+:\{', line):
            # Элемент массива с индексом (0:{, 1:{, etc.)
            # Убираем индекс и оставляем только {
            formatted_lines.append('  ' * current_indent + '{')
            stack.append('{')
            current_indent += 1
        elif ':' in line:
            # Пара ключ:значение
            key, value = line.split(':', 1)
            key = key.strip()
            value = value.strip()

            # Добавляем кавычки к ключу если их нет (включая $)
            if not (key.startswith('"') and key.endswith('"')):
                key = f'"{key}"'

            # Обработка значений
            if value in ['{', '[']:
                # Значение - начало объекта или массива
                formatted_line = f'{key}: {value}'
                formatted_lines.append('  ' * current_indent + formatted_line)
                stack.append(value)
                current_indent += 1
            elif value in ['}', ']']:
                # Не должно происходить, но на всякий случай
                current_indent -= 1
                formatted_line = f'{key}: {value}'
                formatted_lines.append('  ' * current_indent + formatted_line)
                if stack:
                    stack.pop()
            else:
                # Простое значение
                # Добавляем кавычки к строковым значениям если их нет
                if (value and
                    not value.isdigit() and
                    not value.replace('.', '', 1).isdigit() and  # Для чисел с точкой
                    value not in ['true', 'false', 'null'] and
                    not value.startswith('"') and not value.endswith('"') and
                    not value.startswith('{') and not value.startswith('[')):
                    value = f'"{value}"'

                formatted_line = f'{key}: {value}'
                formatted_lines.append('  ' * current_indent + formatted_line)
        else:
            # Простая строка (скорее всего значение в массиве)
            formatted_lines.append('  ' * current_indent + line)

    # Добавляем запятые где необходимо
    result = []
    for i, current_line in enumerate(formatted_lines):

        # Проверяем, нужно ли добавить запятую
        if i < len(formatted_lines) - 1:
            next_line = formatted_lines[i + 1]

            # Определяем, находимся ли мы внутри массива
            in_array = any(bracket == '[' for bracket in stack)

            # Не добавляем запятую если:
            # - текущая строка это { или [
            # - следующая строка это } или ]
            # - текущая строка уже заканчивается запятой
            # - следующая строка начинается с } или ] (для элементов массива)
            should_add_comma = (
                not current_line.endswith('{') and
                not current_line.endswith('[') and
                not current_line.endswith(',') and
                not next_line.strip().endswith('}') and
                not next_line.strip().endswith(']') and
                not next_line.strip().startswith('}') and
                not next_line.strip().startswith(']') and
                not (in_array and next_line.strip() == ']')  # Не добавлять запятую перед закрытием массива
            )

            # Для элементов массива (объектов) добавляем запятую после }
            if (in_array and
                current_line.strip() == '}' and
                next_line.strip() != ']' and
                not next_line.strip().startswith('}')):
                should_add_comma = True

            if should_add_comma:
                current_line += ','

        result.append(current_line)

    return '\n'.join(result)

read_data(locator)

Читает и форматирует JSON-данные из указанного локатора.

Parameters:

Name Type Description Default
locator Any

Локатор элемента с JSON-данными.

required

Returns:

Name Type Description
dict Dict

Распарсенный JSON-объект.

Raises:

Type Description
JSONDecodeError

Если данные не могут быть преобразованы в JSON.

Source code in components\json_container_component.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def read_data(self, locator: Any) -> Dict:
    """Читает и форматирует JSON-данные из указанного локатора.

    Args:
        locator: Локатор элемента с JSON-данными.

    Returns:
        dict: Распарсенный JSON-объект.

    Raises:
        json.JSONDecodeError: Если данные не могут быть преобразованы в JSON.
    """

    # Чтение JSON-содержимого из рабочей области
    loc = self.get_locator(locator)
    json_string = loc.inner_text()

    # Сохранение исходной JSON строки в файл
    with open('json_string.txt', 'w', encoding='utf-8') as f:
        f.write(json_string)
    logger.info("Исходная JSON строка сохранена в файл: json_string.txt")

    formatted_json_string = self.format_json_string(json_string)

    # Сохранение отформатированной JSON строки в файл
    with open('formatted_json_string.txt', 'w', encoding='utf-8') as f:
        f.write(formatted_json_string)
    logger.info("Отформатированная JSON строка сохранена в файл: formatted_json_string.txt")

    try:
        data = json.loads(formatted_json_string)
    except json.JSONDecodeError as e:
        # Дополнительная отладка
        logger.error(f"JSON decode error: {e}")
        logger.error(f"Formatted JSON: {formatted_json_string}")
        assert False, f"Invalid json content. Error: {e}"

    return data