我无法将ndb模型作为JSON返回。
我有一个Game类,如下:
class Game(ndb.Model):
gameID = ndb.StringProperty
gameState = ndb.StringProperty
playerOne = ndb.StringProperty
playerTwo = ndb.StringProperty
def toJSON(self):
jsondata = {
"gameID" : self.key.id(),
"gameState" : self.gameState,
"playerOne" : self.playerOne,
"playerTwo" : self.playerTwo
}
return json.encode(jsondata)
这似乎工作正常,当使用以下代码创建和存储模型时,它可以工作(我认为)
class gameHandler(webapp2.RequestHandler):
def get(self):
gameID = self.request.get("gameID")
gameState = self.request.get("gameState")
playerOne = self.request.get("playerOne")
playerTwo = self.request.get("playerTwo")
game = Game(id=gameID)
game.gameState = gameState
game.playerOne = playerOne
game.playerTwo = playerTwo
game.put()
self.response.write(game.toJSON())
在这种情况下," self.response.write(game.toJSON())"根据需要输出JSON格式的文本,例如:
{"playerTwo":"AI","gameID":"Test2","playerOne":"Peter","gameState":"dog"}
但是,在下面的课程中,我试图简单地将游戏模型检索为JSON,但它会抛出:
TypeError: <class 'google.appengine.ext.ndb.model.StringProperty'> is not JSON serializable
抛出错误的代码:
class getGameHandler(webapp2.RequestHandler):
def get(self):
gameID = self.request.get("gameID")
game = Game.get_by_id(gameID)
self.response.write(game.toJSON())
我很困惑,因为&#34; game.toJSON()&#34;应该给出相同的结果吗?我在代码中犯了一些基本错误吗?
答案 0 :(得分:2)
您的语法不正确,您需要像这样声明您的ndb属性
gameID = ndb.StringProperty()
gameState = ndb.StringProperty()
playerOne = ndb.StringProperty()
playerTwo = ndb.StringProperty()