-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

0

2 Answers 2

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,
            ...
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, so it was the syntax I was missing. Thanks!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.