Я написал приведенный ниже код, чего мне не хватает, я не знаю чего, значение current_table и columns_name появляется перед условием elif, но после того, как внутри elif, почему оно не приходит, я не получаю. Помогите, пожалуйста, чего не хватает и почему значения current_table и columns_name не сохраняются до конца одного цикла.
Пожалуйста, помогите.
import re
import json
def traverse(node, current_table=None):
"""
Traverse the SQL structure to extract tables and columns.
"""
if isinstance(node, dict):
for key, value in node.items():
# If it's a table reference, set current_table
if key == 'table_reference' and isinstance(value, list):
# Join parts like table alias and table name
table_name_parts = [v.get('naked_identifier') for v in value if v.get('naked_identifier')]
table_name = ".".join(table_name_parts)
if table_name:
current_table = table_name
print(f"Table detected: {current_table}") # Debugging
# Handle column references
elif key == 'column_reference' and isinstance(value, dict):
# Extract column name directly from the structure
column_name = value.get('naked_identifier') # Assuming column name is stored here
if column_name: # Ensure column name is valid
print(f"Column detected: {column_name} for table: {current_table}") # Debugging
if current_table:
if current_table not in tables_columns_map:
tables_columns_map[current_table] = []
tables_columns_map[current_table].append(column_name)
else:
print(f"Error: current_table is None when processing column {column_name}")
# Recurse into subnodes
elif isinstance(value, (list, dict)):
traverse(value, current_table) # Continue processing
elif isinstance(node, list):
for item in node:
traverse(item, current_table)
# Example usage:
parsed_data = {
"select_statement": [
{"column_reference": {"naked_identifier": "MI_KEY_ACC_SWITCHING"}},
{"column_reference": {"naked_identifier": "CURRENCY"}},
{"table_reference": [{"naked_identifier": "A_MPAY_BUKDB.ACC_SWITCHING"}]},
{"column_reference": {"naked_identifier": "DEPARTMENT"}}
]
}
tables_columns_map = {}
traverse(parsed_data)
print("Final tables_columns_map:")
print(tables_columns_map)
Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-pyhton
Рекурсия дерева файлов JSON для извлечения имени таблицы и столбца в Python ⇐ JAVA
Программисты JAVA общаются здесь
1733423865
Anonymous
Я написал приведенный ниже код, чего мне не хватает, я не знаю чего, значение current_table и columns_name появляется перед условием elif, но после того, как внутри elif, почему оно не приходит, я не получаю. Помогите, пожалуйста, чего не хватает и почему значения current_table и columns_name не сохраняются до конца одного цикла.
Пожалуйста, помогите.
import re
import json
def traverse(node, current_table=None):
"""
Traverse the SQL structure to extract tables and columns.
"""
if isinstance(node, dict):
for key, value in node.items():
# If it's a table reference, set current_table
if key == 'table_reference' and isinstance(value, list):
# Join parts like table alias and table name
table_name_parts = [v.get('naked_identifier') for v in value if v.get('naked_identifier')]
table_name = ".".join(table_name_parts)
if table_name:
current_table = table_name
print(f"Table detected: {current_table}") # Debugging
# Handle column references
elif key == 'column_reference' and isinstance(value, dict):
# Extract column name directly from the structure
column_name = value.get('naked_identifier') # Assuming column name is stored here
if column_name: # Ensure column name is valid
print(f"Column detected: {column_name} for table: {current_table}") # Debugging
if current_table:
if current_table not in tables_columns_map:
tables_columns_map[current_table] = []
tables_columns_map[current_table].append(column_name)
else:
print(f"Error: current_table is None when processing column {column_name}")
# Recurse into subnodes
elif isinstance(value, (list, dict)):
traverse(value, current_table) # Continue processing
elif isinstance(node, list):
for item in node:
traverse(item, current_table)
# Example usage:
parsed_data = {
"select_statement": [
{"column_reference": {"naked_identifier": "MI_KEY_ACC_SWITCHING"}},
{"column_reference": {"naked_identifier": "CURRENCY"}},
{"table_reference": [{"naked_identifier": "A_MPAY_BUKDB.ACC_SWITCHING"}]},
{"column_reference": {"naked_identifier": "DEPARTMENT"}}
]
}
tables_columns_map = {}
traverse(parsed_data)
print("Final tables_columns_map:")
print(tables_columns_map)
Подробнее здесь: [url]https://stackoverflow.com/questions/79255872/json-file-tree-recursion-for-extracting-the-table-and-column-name-in-pyhton[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия