-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
  • 121,510
  • 29
  • 395
  • 339
Roy Berris
  • 1,502
  • 1
  • 17
  • 40

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,295
  • 1
  • 8
  • 25
0

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

zo0M
  • 972
  • 11
  • 20