Reputation: 175
I'm trying to make an area class that sums up all instances of the key 'area' in a json string.
For example e = Area('[1, 2, 3, {"area": 123, "weight": 1000}]')
should return e=123
and this Area('["Hello", "World", {"area": 999}, {"area": 1}]')
should return 1000.
At the moment I'm just getting 0 returned everytime and I think this may be because I'm initializing sum
too early or because my indexing into the string may be off.
import json
class Area:
def __init__(self, txt):
self.txt=txt
def __str__(self):
sum=0
for a in self.txt:
if a == 'area':
sum+=int(self.txt[a]})
return str(sum)
Upvotes: 1
Views: 105
Reputation: 180391
using json.loads
is fine but you need to make sure you have a dict which you can do with isinstance, you can use the builtin sum function to do the summing for you.
import json
class Area:
def __init__(self, txt):
self.txt = txt
def __str__(self):
return str(sum(d.get("area", 0) for d in json.loads(self.txt)
if isinstance(d, dict)))
Output:
In [8]: e = Area('[1, 2, 3, {"area": 123, "weight": 1000}]')
In [9]: print e
123
In [10]: e = Area('["Hello", "World", {"area": 999}, {"area": 1}]')
In [11]: print e
1000
In your own code you are iterating over the characters in the string as you never call loads
so if a == 'area':
would never be True as you are comparing "area" to each individual char, as is your code would also error as self.txt[a]}
is not valid syntax.
Upvotes: 1
Reputation: 21609
This works.
Then you should test each element of the list to see if it contains an item area
, you should bear in mind that not all items in the list will support the in
operator, so wrap it in an exception block.
Lastly it does seem odd that you are doing all this in the __str__
method. It might be better to have a method that returns
import json
class Area:
def __init__(self, txt):
self.txt = json.loads(txt)
def __str__(self):
sum = 0
for a in self.txt:
try:
if 'area' in a:
sum += int(a['area'])
except TypeError:
pass
return str(sum)
print Area('[1, 2, 3, {"area": 123, "weight": 1000}]')
print Area('["Hello", "World", {"area": 999}, {"area": 1}]')
Upvotes: 0