代码之家  ›  专栏  ›  技术社区  ›  Kalpesh

在python中将嵌套json简化为平面时出现递归错误

  •  1
  • Kalpesh  · 技术社区  · 1 年前

    我正在尝试展平json对象,以便可以从中创建纯csv文件。 但它在投掷

    RecursionError: maximum recursion depth exceeded while calling a Python object
    

    我用python编写的代码,调用simplify_multy_nested_json_recur():

    def simplify_multy_nested_json_recur(obj):
        kv = convert_list_to_kv(obj)
        simplified_json = simplify_nested_json(kv)
        if any(isinstance(value, list) for value in simplified_json.values()):
            simplified_json = simplify_multy_nested_json_recur(simplified_json)
        return simplified_json
    
    def simplify_nested_json(obj, parent_key=""):
        """
        Recursively simplifies a nested JSON object by appending key names with the previous node's key.
        """
        new_obj = {}
        for key in obj:
            new_key = f"{parent_key}_{key}" if parent_key else key
            if isinstance(obj[key], dict):
                new_obj.update(simplify_nested_json(obj[key], parent_key=new_key))
            else:
                new_obj[new_key] = obj[key]
        return new_obj
    
    def convert_list_to_kv(obj):
        """
        Converts list elements into key-value pairs if the list size is 1 in a JSON object.
        """
        for key in obj:
            if isinstance(obj[key], list) and len(obj[key]) == 1:
                obj[key] = obj[key][0]
            elif isinstance(obj[key], dict):
                convert_list_to_kv(obj[key])
        return obj
    

    输入:

    {'resourceType':'CP','id':'af160c6b','period':{'start':'1987-12-21T06:22:41-05:00'},'careTeam':[{'reference':'79a33a776b59'}],'goal':[{'reference':'c14'},{'reference':'b88'}],'activity':[{'detail':{'code':{'coding':[{'code':'160670007','display':'Diabetic diet'}],'text':'Diabetic diet'},'status':'in-progress'}}]}
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Saxtheowl    1 年前

    由于连续递归,您有一个无限循环,因为停止递归的条件永远不会发生。

    以下是我将如何修改您的代码:

    def simplify_multy_nested_json_recur(obj):
        kv = convert_list_to_kv(obj)
        simplified_json = simplify_nested_json(kv)
    
        if any(isinstance(value, dict) for value in simplified_json.values()):
            simplified_json = simplify_multy_nested_json_recur(simplified_json)
        
        return simplified_json
    
    def simplify_nested_json(obj, parent_key=""):
        new_obj = {}
        for key in obj:
            new_key = f"{parent_key}_{key}" if parent_key else key
            if isinstance(obj[key], dict):
                new_obj.update(simplify_nested_json(obj[key], parent_key=new_key))
            else:
                new_obj[new_key] = obj[key]
        return new_obj
    
    def convert_list_to_kv(obj):
        for key in obj:
            if isinstance(obj[key], list) and len(obj[key]) == 1:
                obj[key] = obj[key][0]
            elif isinstance(obj[key], dict):
                convert_list_to_kv(obj[key])
        return obj
    
    推荐文章