[英]How can I structure python objects so they JSONify well?
I'm fairly new to python, coming from js. 我对python很陌生,来自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). 我正在尝试使用json在客户端和服务器之间进行通信,并且在理解python(龙卷风)中容易实现的与对象属性等效的jsonifyable时遇到了麻烦。 Code below for Object creation taken from this SO answer ( https://stackoverflow.com/a/2827726/4808079 ) throws some errors. 下面的用于从该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))
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: 在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? 我应该如何在Python中构造一个对象以使其能够JSON化?
You can encode dicts out of the box: 您可以直接对字典进行编码:
addMe = {
'value': num,
'square': num * num
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.