0

I'm using flask to jsonify a generator that has been listed using the list() command inside a dictionary like so:

r = {
      "stocks": list(current_user.stocks)
     }

But when I try to use jsonify(r) I get the following error:

TypeError: Object of type Stocks is not JSON serializable

In the terminal, if I just print out list(current_user.stocks), it returns me:

[<Stocks GOOGL>, <Stocks TSLA>]

Stocks is a table/class i'm using in flask-sqlalchemy. I want the JSON to look something like this:

{"stocks": [<Stocks GOOGL>, <Stocks TSLA>]}

I have no problem with <Stocks GOOGL> and the other array element being a string.

Any ideia as to how to jsonify this inside a dict? Thanks in advance!

lipebromf
  • 1
  • 2

1 Answers1

0

The example you gave is not a valid JSON. You can try something like:

r['stocks'] = list(map(repr, r['stocks']))

Then jsonify(r) should produce something like:

{"stocks": ["<Stocks GOOGL>", "<Stocks TSLA>"]} # Note that these are strings
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48