[Python]如何使用递归编辑嵌套数组配置值

[Python]如何使用递归编辑嵌套数组配置值,python,json,regex,recursion,config,Python,Json,Regex,Recursion,Config,我有一个配置文件,它由多个嵌套数组和字典组成。我需要有一个文本命令,可以编辑任何变量。这是在Python3中实现的 以下是配置(json)的示例: 命令语法可以更改为其他语法,但其如下所示: !config write joinMsg;help;1 'Try typing !help' 我知道如何以这种方式从配置中读取,但我设置递归的方式意味着我没有办法替换该值 这就是我所拥有的,数组有点像joinMsg;帮助;1具;除沫器: # reads from the config file def

我有一个配置文件,它由多个嵌套数组和字典组成。我需要有一个文本命令,可以编辑任何变量。这是在Python3中实现的

以下是配置(json)的示例:

命令语法可以更改为其他语法,但其如下所示:

!config write joinMsg;help;1 'Try typing !help'
我知道如何以这种方式从配置中读取,但我设置递归的方式意味着我没有办法替换该值

这就是我所拥有的,数组有点像joinMsg;帮助;1具;除沫器:

# reads from the config file
def configRead(arrays):
    try:
        arrays = configSearch(arrays)
        print(arrays)
        output = config
        for r in arrays:
            output = output[r]
    except:
        output = 'No array found'
    return output

# recursive config helper
def configSearch(arrays):
    searchRE = re.match(r'([^;]+);(.+)', arrays, re.I)
    if searchRE:
        output = configSearch(searchRE.group(2))
        output.insert(0, searchRE.group(1))
        return output
    else:
        return [arrays]

这段代码可能很糟糕(我没有经过正式培训),我不知道从这里该怎么做。非常感谢您的帮助。

首先,这里是一个修改后的
configSearch
,它不使用递归,也处理数组索引:

def configSearch(arrays):
    arrays = arrays.split(";")
    return [int(a) if a.isdigit() else a for a in arrays]
然后是一个新函数,
configWrite
,它将编辑配置并用新的
值覆盖
数组

def configWrite(arrays, value):
    arrays = configSearch(arrays)
    print(arrays)
    output = config
    for r in arrays[:-1]:
        output = output[r]
    output[arrays[-1]] = value

是否有一个具体的原因,你试图这样做递归?如果需要的话,可以先迭代,然后再递归。不,它不必是递归的,这只是我能想到的唯一方法。你有什么建议吗?我会把它放在一段时间内,或者在数组中循环,直到找到正确的值,然后用新值替换该索引处的值。就像当前索引时一样!=数组的末尾继续查找。当当前索引==您要查找的索引时,只需将新值插入该索引,该索引将覆盖旧值。我没有在python中与JSON进行过太多的交互,因此这可能不是很有帮助,如果我遇到类似的问题,我会这样做。这几乎就是我在数组中为r使用
时所做的:
一旦我使用递归构建了一个数组名数组。问题是我可以得到值,但路径丢失,除非我从底部递归地重建数组。。。
def configWrite(arrays, value):
    arrays = configSearch(arrays)
    print(arrays)
    output = config
    for r in arrays[:-1]:
        output = output[r]
    output[arrays[-1]] = value