下面的输入是JSON数组。我正在将以下数据传递给我的Python方法。
input={"details": [{"first": [
{"id": "111", "flag": "T", "planName": "PPO"},
{"id": "123", "flag": "F", "planName": "HMO"},
{"id": "133", "flag": "T", "planName": "MA"}],
"second": [{"planName": "PPO", "planRank": "3"},
{"planName": "HMO", "planRank": "4"},
{"planName": "MA", "planRank": "7"}]}]}
下面是JSON现有的文件,
final.json
{"first": [{"id": "111", "flag": "T", "planName": "EPO"},
{"id": "133", "flag": "T", "planName": "HMO"},
{"id": "123", "flag": "T", "planName": "MA"}],
"second": [{"planName": "PPO", "planRank": "1"},
{"planName": "HMO", "planRank": "1"},
{"planName": "MA", "planRank": "1"}]}
当我将上述输入数据传递给我的Python方法时,现有JSON文件中的相应字段应该被更新。从我的输入JSON中,当它与ID的现有JSON匹配时,“标志”和“PrimNeX”应该用从输入JSON传递的值更新。
从第二秒开始,当它与“planName”匹配时,PlanRank应该使用从输入传递的新值进行更新。
预期输出(现有JSON文件应该得到如下更新):
final.json
{"first": [{"id": "111", "flag": "T", "planName": "PPO"},
{"id": "133", "flag": "T", "planName": "MA"},
{"id": "123", "flag": "F", "planName": "HMO"}],
"second": [{"planName": "PPO", "planRank": "3"},
{"planName": "HMO", "planRank": "4"},
{"planName": "MA", "planRank": "7"}]}
我试过下面的代码,但没有成功。
def update_json():
input={"details": [{"first": [
{"id": "111", "flag": "T", "planName": "PPO"},
{"id": "123", "flag": "F", "planName": "HMO"},
{"id": "133", "flag": "T", "planName": "MA"}],
"second": [{"planName": "PPO", "planRank": "3"},
{"planName": "HMO", "planRank": "4"},
{"planName": "MA", "planRank": "7"}]}]}
for x in input:
property = open("final.json")
data = json.load(property)
for y in range(len(data)):
for o in range(len(data['first'])):
if (data['first'][o]['id'] == input[x][0]['id']):
data['first'][o]['planName'] = input[x][0]['planName']
data['first'][o]['flag'] = input[x][0]['flag']
for j in range(len(data['second'])):
print(data['details'][j])
if (data['second'][j]['planName'] == input[x][0]['planName']):
data['second'][j]['planRank'] = input[x][0]['planRank']
with open(("final.json"), 'w') as file:
value = json.dumps(data)
file.write(value)
return "value"