I want to write a Python program which can takes arithmetic expressions in JSON format, parses and evaluates the answer however when using Nested JSON object like the one below. It gives me the error "TypeError: unsupported operand type(s) for +: 'int' and 'list'"
{
"root": { "description":"This is a very deeply first nested expression, and it evaluates to 12.",
"plus": [{
"plus": [{
"plus": [{
"plus": [{
"plus": [{
"int": 2
},
{
"int": 2
}
]
},
{
"int": 2
}
]
},
{
"int": 2
}
]
},
{
"int": 2
}
]
},
{
"int": 2
}
]
}
}
So far I have managed to get this from https://stackoverflow.com/questions/58170675/how-to-use-python-to-return-the-result-of-an-arithmetic-expressions-from-json.
def evaluate_expr(parsed_expr):
val = 0
with open("expression4.json") as complex_data:
data = complex_data.read()
z = json.loads(data)
data = z['root']
for op, val in data.items():
if op == 'description':
pass
elif op == 'plus':
return sum(element[k] for element in data[op] for k in element)
elif op == 'minus' or op == 'times':
if len(data[op]) != 2:
raise ValueError('2 elements expected if operation is minus or times')
nums = [element[k] for element in data[op] for k in element]
if op == 'minus':
return abs(nums[0] - nums[1])
else:
return nums[0] * nums[1]
else:
raise ValueError('Invalid operation')
How would I iterate over the above Nested JSON Object recursively to evaluate the expression.