вот мой код def decoder(jsonstr): '''Десериализовать json-строку с учетом вложенных…
- User
вот мой код def decoder(json_str): '''Десериализовать json-строку с учетом вложенных структур''' try: result = json.loads(json_str) except: return json_str if isinstance(result, list): if len(result) == 1: result = result[0] else: result_dict = {} for d in result: result_dict.update(d) result = result_dict if isinstance(result, int) or isinstance(result, str): return result for key, value in result.items(): try: result[key] = decoder(value) except TypeError: result[key] = value return result
def get_path_value(json_str, path): '''Получить значение параметра из пути в json-строке''' points = path.split('/')[1:] target = decoder(json_str)
for index, point in enumerate(points): if '[' in point: pattern = r'\[(\d)\]' match = re.search(pattern, point) number = int(match.group(1)) point = point[:point.find('[')] target = target.get(point)[number] continue if isinstance(target, list): if len(target) == 1: target = target[0] else: try: result = [] for i in target: result.append(i.get(points[-1])) return result except Exception as e: errorfile.write(f'{json_str};{path}' + '\n') return None try: if isinstance(target, str): return target target = target.get(point) if index == 0 and not target: try: return get_path_value(json_str, f'/{list(decoder(json_str).keys())[0]}'+path) except Exception as e: errorfile.write(f'{json_str};{path}' + '\n') return None if point == points[-1]: return target except Exception as e: errorfile.write(f'{json_str};{path}' + '\n') return Noneвот строка которую обрабатываю { "error_message": "Успех", "result": { "CUR_MODEL": "NULL", "Total_debt_max24": "NULL", "pilot_ki_flag": "n", "rsk_fin": null, "skip_calc_flag": false, "OnsiteAudit": "NULL", "WZ50_250_flag": "NULL", "target_sure_code": "NULL", "cl_total_debt_agr_sum": 587500, "NeedRecalc": null, "lim_kbk_micro": null, "TotalValue": "Отказ", "dbo_dt_day": null, "Cl_total_debt_wo_Agr_sum_KG": "NULL", "alt_term": "NULL", "SUM_CARD": "NULL", "lim_fin_dov": null, "smp_manual_flag_calc": "n", "Rw_use_flag": "y", "alt_limit": "NULL", "alt_product": "NULL", "Guarantee": "NULL", "invest_real_estate": "n", "flag_reclassification": "NULL", "lim_fin_goz": null, "group": 2, "ske_goz": null, "CalcRBL": "NULL", "TERM_CARD": "NULL", "actual_rating_flag": null, "lim_fin": null, "TERM_APP": "NULL", "cl_total_debt_agr_sum_kg": 587500, "flag_conflict": "NULL", "FIN": "NULL", "smp_manual_flag": "NULL", "ske_micro": 5000000, "Code": "TVR93;TVR94;TVR73;TVR63", "AlternativeRoute": "NULL", "BorrowerSegment": "NULL", "first_reg_dt_days": 2466, "Manual_rs_flag": "NULL", "SUM_APP": "NULL", "armodel_2_0_flag": "NULL" }, "context": { "total_value": "Отказ", "is_young": true, "skip_calc_flag": false, "pd_calc": 0.58275, "target_sure_code": "NULL", "cl_total_debt_agr_sum": 587500, "fin": "NULL", "is_sup_available": true, "alternative_route": "NULL", "pre_route": { "area_reliability": 4, "total_value": "Отказ", "gz_flag": 0, "standard_u": "y", "pd_calc": 0.58275, "check_kbk_commodity": 0, "empty_scores": false, "rw_calc": 25, "r_standalone_irb": 14, "bad_sp": null, "context": null, "toxic_client_flag": 0, "std": "", "change_ownership_180": 0, "credit_history_ext_bor": 4, "check_refuse_flag": 1, "sum_deal": 0, "term_credit_month": 36, "overdue_int_pers": 0, "limit_vkl_goz": 0, "no_easy_product": 0, "stop_21": 0, "neuro_score_bki": -5.3323803146, "debt_active_loans": 4649341.99, "credit_history_int_kg": 1, "reg_online": "2017-11-29", "bad_sup": 0, "net_incm": null, "quant_okved_1": "49", "sign_problems": "зеленая", "first_reg_dt": "29-11-2017", "no_easy_product_light": 0, "product_limit_mcx": null, "reg_dt": "2017-11-29", "restr_deal_flag": null, "toxic_client_dict_data": [ { "first_reg_dt_days": 1460, "client": "ИП", "cl_total_debt_agr_sum": 1300000, "total_delinq_6m": 3 } ], "quant_okved_3": null, "gov_support_program": 99, "quant_okved_2": "41", "curr_debt": 87500, "product_limit": null, "credit_history_int_own": 4, "product": 3, "appl_type": 1, "address_code_legal": 32, "ske_micro_log": 3000000, "el2": 26.5792275, "eL_limit": 0, "crm_segm": "Микро", "net_assets": null, "osz_el_limit": 0, "score_bki_borr": -3.0630562607, "credit_history_ext_kg": 4, "risk_segment": "ММБ Розничный", "DATA_IRB": { "data": null, "ar_revenue": null, "ip_reg_first_dt": "2017-10-19", "inn": null, "LOAD_IRB": { "ar_revenue": null, "ip_reg_first_dt": "2017-10-19", "inn": null, "ul_reg_first_dt": null, "capital_sum": null, "cur_default": 0, "pd_pit": 0.016446020312, "total_delinq_6m": 0, "cl_cur_max_delinq": 0 }, "ul_reg_first_dt": null, "capital_sum": null, "cur_default": 0, "inn_exists": true, "pd_pit": 0.016446020312, "total_delinq_6m": 0, "cl_cur_max_delinq": 0 }, "check_refuse_params": [ "TVR93;TVR94;", 1 ], "eL_limit_msh": null, "plurality_flag": 0, "reg_cloud": null, "armodel_2_0_result": null, "use_el2": false, "osz_microcredit": 0, "skip_calc_flag": false, "data": null, "source": 1, "ALL_BILL_GAR": 0, "is_sup_available": true, "probesc": 0, "ctrl_dt": "2002-07-01", "now_dt": null, "ar_check_done": null, "dbo_date": null, "credit_history_int_bor": 1, "is_welcome": false, "curr_debt_kg": 87500, "scope_3": false, "check_refuse_code": "TVR93;TVR94;", "el": 40.41954, "scope_2": false, "scope_1": false, "score_bki_guar_mean": -4.3478043716, "overdue_ext_business": 26569.6, "overdue_ext_pers": 26569.6, "target_sure": 72, "limit_kbk_commodity": 87500, "rating_model_flag": null, "request": null, "SCORE_BKI": -3.1732451305, "code": "", "gosb_code": "8605", "check_refuse": [ "TVR93;TVR94;", 1 ], "table_step": null, "sum_deal_micro": 0, "stop_10": 0, "not_welcome": true, "score_application_sme": null, "pilot_trust_flag": "y", "address_code_egr": null, "coll_mat": 0, "ske_goz": null, "sum_deal_goz": 0, "stop_1": 0, "warning_flag": 1, "stop_3": 0, "dbo_dt": null, "credit_history_ext_own": 4, "stop_9": 0, "address_code_fact": 32, "agr_sum": 500000, "ske_micro": 5000000, "stop_6": 0, "stop_7": 0, "target": 2, "ske_el_card": -87500, "overdue_int_business": 0, "micro": 1, "is_uncredited_region": { "acr_sp": false, "scope_3": false, "acr_rj": false, "scope_2": false, "scope_1": false } }, "empty_scores": false, "rw_calc": 25, "dbo_dt_day": null, "alt_term": "NULL", "r_standalone_irb": 14, "cl_total_debt_wo_agr_sum_kg_calc": 87500, "wz_50_250_flag": "NULL", "is_goszakaz": false, "smp_manual_flag_calc": "n", "toxic_client_flag": null, "alt_product": "NULL", "flag_reclassification": "NULL", "group": 2, "is_ip": true, "rw_use_flag": "y", "actual_rating_flag": null, "check_refuse_code": "TVR93;TVR94;", "el": 40.41954, "check_refuse_flag": 1, "cl_total_debt_agr_sum_kg": 587500, "route": { "area_reliability": 4, "total_value": "Отказ", "gz_flag": 0, "standard_u": "y", "pd_calc": 0.58275, "check_kbk_commodity": 0, "rsk_int_ul": null, "pre_route": null, "empty_scores": false, "rw_calc": 25, "rsk_max_util": null, "el_limit": 0, "r_standalone_irb": 14, "fin_lim_welcome": null, "fin_prod_welcome": null, "bad_sp": null, "context": null, "lim_fin_dov": null, "interest_rate": null, "vbok_rnd": null, "std": "", "is_critical_code_ncl": null, "change_ownership_180": 0, "credit_history_ext_bor": 4, "check_refuse_flag": 1, "sum_deal": 0, "term_credit_month": 36, "ep_trans_ip": null, "overdue_int_pers": 0, "total_value_ncl": null, "limit_vkl_goz": 0, "actual_rating_flag_calc": null, "kbk_v_n_fin": null, "tpdl": null, "no_easy_product": 0, "stop_21": 0, "neuro_score_bki": -5.3323803146, "debt_active_loans": 4649341.99, "credit_history_int_kg": 1, "reg_online": "2017-11-29", "rsk_max": null, "rsk_trans_ip": null, "bad_sup": 0, "net_incm": null, "quant_okved_1": "49", "sign_problems": "зеленая", "code_ncl": null, "first_reg_dt": "29-11-2017", "no_easy_product_light": 0, "lim_max": null, "vbok_flag": null, "reg_dt": "2017-11-29", "restr_deal_flag": null, "quant_okved_3": null, "gov_support_program": 99, "quant_okved_2": "41", "curr_debt": 87500, "ske_micro_kbk_v_n1": null, "term": null, "ske_micro_kbk_v_n2": null, "product_limit": null, "credit_history_int_own": 4, "lim_fin_kbk": null, "product": 3, "appl_type": 1, "f": null, "address_code_legal": 32, "el2": 26.5792275, "k": null, "crm_segm": "Микро", "net_assets": null, "osz_el_limit": 0, "score_bki_borr": -3.0630562607, "credit_history_ext_kg": 4, "dic_data": { "ar_cutoff": 0.55, "k_10": 0.9, "ip_k2": 0.75, "k_13": 0.81, "k_14": 0.72, "k_11": 0.9, "k_12": 0.9, "k_17": 0.36, "k_18": 0.27, "k_15": 0.63, "t_invest": 12, "k_16": 0.54, "program": "No", "ab_test_percent": 50, "k_19": 0.27, "avg1_k3": 0.4, "rate": "29.5;29.5;29.5;29.5;29.5;29.5;29.5;29.5;29.5;29.5;29.5;34.8;29.5;39.9;29.5;18.0", "ip_cutoff": 30, "ul_cutoff": 100, "avg3_k3": 2, "k_20": 0, "k_21": 0, "k_7": 0.9, "k_6": 0.9, "k_24": 0, "k_9": 0.9, "k_25": 0, "k_8": 0.9, "f": 20, "k_22": 0, "k_23": 0, "k_26": 0, "ul_k2": 1, "check_cutoff": "n", "name": "Программа льготного кредитования отсутствует", "avg4_k3": 4, "cutoff": 0.26185, "avg2_k3": 1, "t_oborot": 12 }, "risk_segment": "ММБ Розничный", "DATA_IRB": { "data": null, "ar_revenue": null, "ip_reg_first_dt": "2017-10-19", "inn": null, "LOAD_IRB": { "ar_revenue": null, "ip_reg_first_dt": "2017-10-19", "inn": null, "ul_reg_first_dt": null, "capital_sum": null, "cur_default": 0, "pd_pit": 0.016446020312, "total_delinq_6m": 0, "cl_cur_max_delinq": 0 }, "ul_reg_first_dt": null, "capital_sum": null, "cur_default": 0, "inn_exists": true, "pd_pit": 0.016446020312, "total_delinq_6m": 0, "cl_cur_max_delinq": 0 }, "cutoff": null, "check_refuse_params": [ "TVR93;TVR94;", 1 ], "plurality_flag": 0, "route_code": "TVR73;TVR63;", "reg_cloud": null, "vbok_k": null, "armodel_2_0_result": null, "use_EL2": false, "osz_microcredit": 0, "skip_calc_flag": false, "data": null, "fin_lim_fin_ecom": null, "f_rnd": null, "average_revenue": null, "rsk_final": null, "source": 1, "ALL_BILL_GAR": 0, "is_sup_available": true, "probesc": 0, "ctrl_dt": "2002-07-01", "now_dt": null, "ar_check_done": null, "dbo_date": null, "term_programm": null, "wz_50_250_flag_calc": "n", "credit_history_int_bor": 1, "ep_int_ul": null, "curr_debt_kg": 87500, "scope_3": false, "check_refuse_code": "TVR93;TVR94;", "lim_fin": null, "el": 40.41954, "scope_2": false, "rsk_trans_ul": null, "scope_1": false, "ncl_final_flag": null, "score_bki_guar_mean": -4.3478043716, "overdue_ext_business": 26569.6, "ep_trans_ul": null, "overdue_ext_pers": 26569.6, "target_sure": 72, "limit_kbk_commodity": 87500, "rating_model_flag": null, "request": null, "SCORE_BKI": -3.1732451305, "gosb_code": "8605", "armodel_final_flag": null, "check_refuse": [ "TVR93;TVR94;", 1 ], "rsk_result_oborot": null, "table_step": null, "lim_kbk_micro": null, "sum_deal_micro": 0, "lim_fin_ecom": null, "stop_10": 0, "total_value_armodel": null, "coeff_ncl": null, "score_application_sme": null, "address_code_egr": null, "lim_fin_goz": null, "coll_mat": 0, "ske_goz": null, "sum_deal_goz": 0, "stop_1": 0, "warning_flag": 1, "stop_3": 0, "dbo_dt": null, "credit_history_ext_own": 4, "stop_9": 0, "address_code_fact": 32, "fin_term_welcome": null, "agr_sum": 500000, "ske_micro": 5000000, "stop_6": 0, "armodel_2_0_flag_calc": "n", "stop_7": 0, "target": 2, "ske_el_card": -87500, "overdue_int_business": 0, "micro": 1, "need_recalc_flag": null, "armodel_total_value_flag": null, "lim_ecom_flag": null, "lim_ecom_k2": null, "is_uncredited_region": { "acr_sp": false, "scope_3": false, "acr_rj": false, "scope_2": false, "scope_1": false }, "lim_ecom_k3": null }, "credit_history": null, "first_reg_dt_days": 2466, "need_recalc": null, "debt_to_rev_ratio": null, "problem_client": 0, "pilot_ki_flag": "n", "check_okved": { "toxic": "ИП", "code": "49.41", "route": null, "name": "Деятельность автомобильного грузового транспорта" }, "code": "TVR93;TVR94;TVR73;TVR63", "borrower_segment": "NULL", "pilot_RSK": null, "table1_term_credit_month": 36, "guarantee": "NULL", "check_refuse": [ "TVR93;TVR94;", 1 ], "is_doverie": true, "term_card": "NULL", "first_reg_dt": "29-11-2017", "sum_card": "NULL", "borrower_segment_calc": "Микро", "table1_agr_sum_min": 100000, "alt_limit": "NULL", "invest_real_estate": "n", "term_app": "NULL", "cur_model": "NULL", "onsite_audit": "NULL", "cl_total_debt_wo_agr_sum_kg": "NULL", "total_debt_max24": "NULL", "is_izhs": false, "have_col": false, "flag_conflict": "NULL", "el2": 26.5792275, "smp_manual_flag": "NULL", "sum_app": "NULL", "toxic_client": null, "calc_rbl": "NULL", "manual_rs_flag": "NULL", "risk_segment": "ММБ Розничный", "armodel_2_0_flag": "NULL", "is_uncredited_region": { "acr_sp": false, "scope_3": false, "acr_rj": false, "scope_2": false, "scope_1": false }, "table1_agr_sum_max": 250000000 }, "error_code": "0" } get_path_value(x, '/route/total_value_ncl') дает на выходе "Успех", то есть не то что нужно. исправь мой код
- Assistant
В вашем коде есть несколько моментов, которые нужно исправить или улучшить. Основная проблема в том, что функция неправильно обрабатывает JSON-строку, что приводит к не тому результату при использовании функции .
- User
вытаскивает None
- Assistant
Если функция
get_path_value()возвращаетNone, это может происходить по нескольким причинам. Возможно, указанное вами вpathместоположение данных отличается от реальной структуры JSON. Убедитесь, что путь является корректным и данные находятся по указанному пути. Давайте ещё раз внимательно разберём код и попробуем его улучшить: - User
мне нужно отобрать данные после агрегации в sql. можно ли написать так? having ('a', 'b', 'c') in column
- Assistant
В SQL оператор
HAVINGиспользуется для фильтрации результатов после выполнения агрегатных функций (таких какSUM,COUNT,AVG, и т.д.). Однако, используя простоHAVING ('a', 'b', 'c') in columnв SQL-запросе, вы получите ошибку, потому что SQL не поддерживает такой синтаксис для оператораHAVING.Если ваша цель заключается в том, чтобы отфильтровать агрегированные результаты, где значения в определённом столбце соответствуют любому из значений в указанном списке, вы можете использовать оператор
INследующим образом:SELECT column1, COUNT(*) FROM your_table GROUP BY column1 HAVING column1 IN ('a', 'b', 'c');Разберём пример:
column1— это столбец, который вы группируете.your_table— это имя вашей таблицы.HAVING column1 IN ('a', 'b', 'c')— это условие для фильтрации агрегированных групп, гдеcolumn1имеет одно из значений в указанном списке.
Этот запрос сгруппирует данные по
column1и затем отфильтрует группы, оставляя только те, где значение равно 'a', 'b' или 'c'. Убедитесь, что действительно содержит текстовые значения, иначе SQL выбросит ошибку типа данных. - User
приведи пример
- Assistant
Давайте рассмотрим пример SQL-запроса на примере таблицы, содержащей информацию о продажах продуктов. Таблица может иметь следующие столбцы:
product_category,sales_amountи другие. Предположим, что вы хотите агрегировать данные по категориям продуктов и получить только те категории, которые находятся в списке значений (например, 'Electronics', 'Furniture', 'Toys').Вот как может выглядеть этот запрос:
SELECT product_category, SUM(sales_amount) AS total_sales FROM sales GROUP BY product_category HAVING product_category IN ('Electronics', 'Furniture', 'Toys');Объяснение:
-
SELECT product_category, SUM(sales_amount) AS total_sales: выбираем категорию продукта и сумму продаж по этой категории.
SUM(sales_amount)вычисляет общую сумму продаж для каждой категории, а задаёт имя для этого агрегированного столбца.
-
- User
а если в ячейке будет ‘Electronics, Boy’, то having отберет ее?
- Assistant
Если значение в столбце
product_categoryсодержит строку'Electronics, Boy'и вы используете условиеHAVING product_category IN ('Electronics', 'Furniture', 'Toys'), то эта строка не будет выбрана, потому чтоHAVING ... IN (...)ищет точное соответствие с одним из перечисленных значений.Если вам нужно выбрать строки, в которых столбец может содержать подстроку, такая как 'Electronics', вы можете использовать
LIKEсHAVING, комбинируя его с операторомGROUP_CONCATдля агрегации строк. Это можно сделать следующим образом:SELECT product_category, SUM(sales_amount) AS total_sales FROM sales GROUP BY product_category HAVING product_category LIKE '%Electronics%' OR product_category LIKE '%Furniture%' OR product_category LIKE '%Toys%';В этом примере:
LIKE '%Electronics%'ищет 'Electronics' в любой части строки.- Если в столбце
product_categoryприсутствует 'Electronics' как часть значения, строка будет выбрана.