i have this piece of code in testing currently
from_api_response_data = [
{
"active": True,
"available": True,
"test1": True,
"test2": "Testing Only",
"test3": False,
"test_name": "Tester 1",
"id": "12345abcxyz",
"test_url": {
"url": "/something/others/api/v1/abc123"
}
},
{
"active": True,
"available": True,
"test1": False,
"test2": "This also a test",
"test3": False,
"test_name": "Tester 2",
"id": "12345abcxyz678",
"test_url": {
"url": "/something/others/api/v1/abc1234"
}
}
]
filename = 'testingfile.json'
today = datetime.datetime.now().isoformat()
from_api_response_data.append(
{
'last_updated_date': today
}
)
Path(filename).write_text(
json.dumps(from_api_response_data, default=vars, indent=2)
)
test_file_json_read = json.loads(
Path(filename).read_text()
)
for test in test_file_json_read:
if test['available']:
print("true available")
what i am trying to simulate is getting data from api and append updated date and write the data into json file. If i remove that part in appending date, my code works fine when finding test['available']
from console output
true available
true available
but with the date append, i will have this error
if test['available']:
KeyError: 'available'
i am not sure why i am not able to read the test['available'] if the date is appended
this is what my testingfile.json showing
[
{
"active": true,
"available": true,
"test1": true,
"test2": "Testing Only",
"test3": false,
"test_name": "Tester 1",
"id": "12345abcxyz",
"test_url": {
"url": "/something/others/api/v1/abc123"
}
},
{
"active": true,
"available": true,
"test1": false,
"test2": "This also a test",
"test3": false,
"test_name": "Tester 2",
"id": "12345abcxyz678",
"test_url": {
"url": "/something/others/api/v1/abc1234"
}
},
{
"last_updated_date": "2022-11-25T09:48:12.765296"
}
]
CodePudding user response:
This is happening because the last dictionary this