-1

I am trying to make my object from and to JSON. This object uses SQL Alchemy so using json.dumps(vars(self)) doesnt work. I am looking for the syntax to make this possible.

    def to_json(self):
        obj = {
            self.won,
            self.gameOver,
            self.allowMultiColor,
            self.pattern,
            self.board,
            self.round,
            self.totalRounds
        }

        return json.dumps(obj)

And then I want to redefine fields like this:

    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']

the to_json method doesnt' work. And when I try to get it again I get this error: TypeError: list indices must be integers or slices, not str

I am new to python so I don't yet know all the fancy syntax

davidism
  • 110,080
  • 24
  • 357
  • 317
Roy Berris
  • 1,310
  • 1
  • 13
  • 34

2 Answers2

1

obj must to be a dictinary to allow using strings as indices. So obj should look like this

obj = {
            'won':self.won,
            'gameOver':self.gameOver,
            ...
        }
Banana
  • 2,053
  • 1
  • 7
  • 23
0

you can pass sqlalchemy objects into marshmallow's scheme, defining it's attributes into marshmallow's scheme. no problem with it.

zo0M
  • 415
  • 6
  • 14