The below input is the JSON Array. I am passing the below data to my Python method.
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"}]}]}
The below is the JSON existing file,
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"}]}
When I pass the above input data to my Python method the corresponding fields in the existing JSON files should get updated.From my input JSON when it matches with existing JSON of id then 'flag' and 'planname' should be updated with the passing values from input JSON.
and from second when it matches with 'planName' then PlanRank should be updated with new values passing from the input.
Expected Output(Existing JSON file should get the update like below):
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"}]}
I have tried the below code but no luck.
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"
input['details'][0]?dataobject is being loaded. It looks like you are saving the data to a file after you update it and then return a string that just says"value". Also, the input array is nested under thedetailskey, so you may want to actually iterate throughfor x in input['details']: