我必须执行一些测试来调优JSON文件的一些数值参数。
为了简单起见,我用字符串“variable”替换了所有这些值,然后执行以下操作:
numeric_vals = [10,20, 30, 40] # numeric values to replace in that order
with open ('mypath') as my_file:
json_str = my_file.read()
for i in numeric_vals:
json_str = json_str.replace("\"variable\"", str(i), 1)
c = json.loads(json_str) #loading in order to work with
这很好用,但有没有更有效的方法呢?需要替换的值在不同的深度,可能在列表等中。我的JSON文件是15KB,我需要测试很多(真的很多!)配置。在每个测试中,大约200个变量需要被替换。我使用的是python 2.7,但python 3.5也是一个选项。
谢谢你的帮助!
编辑:
这是我口述的一个例子。应该注意的是,真实的东西要长得多,也要深得多:
{
"1": {
"transition": {
"value": "variable", # edit here
"unite": "sec"
},
"sequence": [
{
"step": "STEP",
"name": "abc",
"transition": {
"value": "variable", #edit here
"unite": "sec"
},
"entity": "aa",
"_equipement": 3,
"_value": 0
},
{
"step": "FORK",
"BRANCHES": [
{
"": {
"sequence": [
{
"step": "STEP",
"name": "klm",
"transition": {
"value": "variable", # edit here
"unite": "sec"
},
"entity": "vvv",
"_equipement": 10,
"_value": 0,
"conditions": [
[
{
"name": "ddd",
"type": "el",
"_equipement": 7,
"_value": 1
}
]
]
}
]
}
},
{
"SP": {
"sequence": [
{
"step": "STEP",
"name": "bbb",
"transition": {
"value": "variable", # edit here
"unite": "sec"
},
"entity": "bb",
"_equipement": 123,
"_value": 0,
"conditions": [
[
{
"name": "abcd",
"entity": "dgf",
"type": "lop",
"_equipement": 7,
"_valeur": 0
}
]
]
}
]
}
}
]
}
]
}
}