Could someone help as to why this code isn’t working? it is supposed to return 40.
def get_total(transaction_json, category):
n = 0
x = len(transaction_json)
z = 0
while n < x:
a = transaction_json[n]
y = json.loads(a)
if y["category"] == category:
z = z + y["amount"]
else:
z = z
n = n + 1
return(z)
get_total("[{"category":"food","amount":30}
{"category":"fuel","amount":40},
{"category":"transport","amount":10},
{"category":"holidays","amount":50},
{"category":"entertainment","amount":20}]","fuel")
this is outputting a very long error:
Traceback (most recent call last):
File "C:/Users/ricky/AppData/Local/Programs/Python/Python312-32/123.py", line 16, in <module>
get_total("[{"category":"food","amount":30},{"category":"fuel","amount":40},{"category":"transport","amount":10},{"category":"holidays","amount":50},{"category":"entertainment","amount":20}]","fuel")
File "C:/Users/ricky/AppData/Local/Programs/Python/Python312-32/123.py", line 8, in get_total
y = json.loads(a)
File "C:UsersrickyAppDataLocalProgramsPythonPython312-32Libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:UsersrickyAppDataLocalProgramsPythonPython312-32Libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:UsersrickyAppDataLocalProgramsPythonPython312-32Libjsondecoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
9
Here’s the corrected version of your code:
import json
def get_total(transaction_json, category):
transactions = json.loads(transaction_json)
total = 0
for transaction in transactions:
if transaction["category"] == category:
total += transaction["amount"]
return total
transaction_data = """[
{"category":"food","amount":30},
{"category":"fuel","amount":40},
{"category":"transport","amount":10},
{"category":"holidays","amount":50},
{"category":"entertainment","amount":20}
]"""
print(get_total(transaction_data, "fuel"))
Explanation:
- JSON Syntax: The JSON string now correctly uses commas between dictionaries and square brackets around the list.
import json
at the top: Theimport
statement is moved outside the loop.- Parsing once: The
json.loads
function is used to parse the entire JSON string into a list of dictionaries, which is then iterated over in the loop.
This code should now correctly output 40 when you run it.
3