我是来自js的python的新手。
我正在尝试使用json在客户端和服务器之间进行通信,并且我无法理解python(龙卷风)中对象属性的易于jsonifyable等价物。从这个SO答案(https://stackoverflow.com/a/2827726/4808079)获取的对象创建的代码会引发一些错误。
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))
控制台错误:
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
相当于我在上面尝试的内容就像在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);
我应该如何在Python中构建一个对象以便JSON化好?
答案 0 :(得分:2)
您可以直接编码dicts:
addMe = {
'value': num,
'square': num * num
}