如何用动态值替换JSON中的特定键的值

时间:2018-07-16 12:01:59

标签: json python-3.x

我在文件中有一个很大的JSON响应,并且想用动态值更改特定键的值。我们从搜索到的键值中获得的动态值。因此,该密钥可能位于顶层,也可能是嵌套的,但我们永远不知道该密钥的确切路径。我设法搜索了键及其路径,例如s.[0].v.[23].ggg,但无法创建实际的路径,例如['s'][0]['v'][23['ggg']。 可以帮助身体找到这个。 下面的脚本给出类似的输出

['.Attributes[2]']['bestTime'] => Jun 25, 2018 6:00:00 AM

但是我正在寻找类似.p的格式的输出。

['Attributes'][2]['bestTime'] => Jun 25, 2018 6:00:00 AM

测试数据如下,我想通过操作自己的值来更改"bestaartureTime"的值。

str = {"lAttributes":[{"Identifier":{"newIdentifier":{"DDline":"BM","guideIdDate":"Jun 25, 2018 12:00:00 AM","guideNo":"MM","suffix":"A"},"origin":"FRY","destination":"DZ"},"guideOwner":"VX","guideRegistration":"DD","guideType":"44","bestaartureStatus":"S","bestaaTime":"Jun 25, 2018 6:00:00 AM","bestaaStatus":"S","bestaartureTime":"Jun 25, 2018 5:00:00 AM","compartments":[{"code":"DD","guideCapacity":8,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":10,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":32,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":24,"guideBooked":0,"guideForecast":0}]}]}

list_k = ['w','r']    
def traverse(path, str):
        count = -1
        if isinstance(str, dict):
            d = str
            for k, v in d.items():
                if isinstance(v, dict):
                    traverse(path + "." + k, v)

                elif isinstance(v, list):
                    traverse(path + "." + k, v)

                else:
                    if k in list_k:
                        print("[\'"+path +"\']"+ "[\'"+k+"\']", "=>", v)

        if isinstance(str, list):
            li = str
            for e in li:
                count += 1
                if isinstance(e, dict):
                    traverse("{path}[{count}]".format(path=path, count=count), e)
                elif isinstance(e, list):
                    traverse("{path}[{count}]".format(path=path, count=count), e)
                else:    
                    print("[{path}][{count}] => {e}".format(path=path, count=count, e=e))

0 个答案:

没有答案