I'm fairly new to python, coming from js.
I'm trying to communicate between client and server using json, and I'm having trouble understanding what the easily jsonifyable equivalent to an object attribute is in python (tornado). Code below for Object creation taken from this SO answer (https://stackoverflow.com/a/2827726/4808079) throws some errors.
class MainHandler(tornado.web.RequestHandler):
def post(self):
#getting and parsing json works as expected
args = json.loads(self.request.body.decode())
#can't seem to figure out how to make this jsonify well
out = []
for num in range(0,5):
addMe = type('', (), {})
addMe.value = num
addMe.square = num * num
out.append(addMe)
self.write(json.dumps(out))
Console Error:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/tornado/web.py", line 1509, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "test_tornado.py", line 43, in post
self.write(json.dumps(out))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <class '__main__.'> is not JSON serializable
The equivalent of what I'm trying to above would be like so, in JavaScript:
var out = []
for(var num = 0; num < 5; num++) {
var addMe = {};
addMe.value = num;
addMe.square = num*num;
out.push(addMe);
}
return JSON.stringify(out);
How am I supposed to structure an object in Python so that it JSONifies well?