我正在嘗試將我的對象從和到 JSON。此對象使用 SQL 煉金術,因此使用不起作用。我正在尋找使這成為可能的語法。json.dumps(vars(self)) def to_json(self): obj = { self.won, self.gameOver, self.allowMultiColor, self.pattern, self.board, self.round, self.totalRounds } return json.dumps(obj)然后我想重新定義這樣的字段: def from_json(self, json_string): obj = json.loads(json_string) self.won = obj['won'] self.gameOver = obj['gameOver'] self.allowMultiColor = obj['allowMultiColor'] self.pattern = obj['pattern'] self.board = obj['board'] self.round = obj['round'] self.totalRounds = obj['totalRounds']該方法不起作用。當我嘗試再次獲取它時,我收到此錯誤:to_jsonTypeError: list indices must be integers or slices, not str我是python的新手,所以我還不知道所有花哨的語法
1 回答

哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
obj 必須是字典才能允許使用字符串作為索引。所以obj應該看起來像這樣
obj = {
'won':self.won,
'gameOver':self.gameOver,
...
}
添加回答
舉報
0/150
提交
取消