简体   繁体   中英

How can I structure python objects so they JSONify well?

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?

You can encode dicts out of the box:

addMe = {
    'value': num,
    'square': num * num
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM