简体   繁体   English

我该如何构造python对象,使它们能够很好地进行JSON化?

[英]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.

相关问题 对于我的Quicksort算法,我该如何使它对字符串和对象也进行排序? - For my Quicksort algorithm how can I make it so that it sorts Strings and objects as well? 如何从SQLAlchemy的JSON对象? - How to jsonify objects from sqlalchemy? 如何使用自定义jsonification对包含对象的数组进行json化 - how to jsonify an array containing objects with custom jsonification 如何构造我的RequireJS项目,以便可以对其进行优化? - How do I structure my RequireJS project so that it can be optimized? 我如何在导航栏中进行更改,以便它也响应移动视图 - How can i make changes in the navbar so that it is responsive to mobile view as well 如何在JavaScript中合并两个具有不同结构的对象? - How can I concat two objects with different structure in Javascript? 如何将动态对象添加到嵌套数组中,使其包含相似的结构 - How to add dynamic objects into the nested array so that it will contain similar structure 如何构建基于 Backbone.View 的插件,以便可以单独扩展其嵌套视图? - How can I structure a Backbone.View based plugin so that its nested views can be extended individually? 如何在 Python 中使用 Flask 压缩/最小化 JSON/Jsonify 的大小? - How to compress/minimize size of JSON/Jsonify with Flask in Python? 如何将字符串数组转换为对象,以便可以将这些对象拆分为键值对? - How to covert an array of strings into objects so that I can split those objects into key value pairs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM