Рекурсия дерева файлов JSON для извлечения имени таблицы и столбца в PythonJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Рекурсия дерева файлов JSON для извлечения имени таблицы и столбца в Python

Сообщение 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)


Подробнее здесь: https://stackoverflow.com/questions/792 ... -in-pyhton
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»