私はjsから来て、かなり新しいpythonです。Pythonオブジェクトを構造化して、JSON化できるようにするにはどうすればよいですか?
私はjsonを使用してクライアントとサーバーの間で通信しようとしていますが、オブジェクト属性に相当するjsonifyableがpython(竜巻)に何であるかを理解できません。この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);
私は構造化することが出来るのですかそれはJSONifiesようにPythonのオブジェクトですか?
のsimplejsonをチェックアウト - https://simplejson.readthedocs.io/en/latest/ – MikeJ
さて、あなたのトレースバック** **は完全ではありません。例外は何ですか? – freakish
'type( ''、()、{})'はどこで使われていましたか?それは非常に奇妙な考えです。 –