简体   繁体   English

Flask:jsonify 列出的生成器

[英]Flask: jsonify listed generator

I'm using flask to jsonify a generator that has been listed using the list() command inside a dictionary like so:我正在使用 flask 对已使用list()命令在字典中列出的生成器进行 jsonify,如下所示:

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

But when I try to use jsonify(r) I get the following error:但是当我尝试使用jsonify(r)时,出现以下错误:

TypeError: Object of type Stocks is not JSON serializable TypeError:股票类型的 Object 不是 JSON 可序列化的

In the terminal, if I just print out list(current_user.stocks) , it returns me:在终端中,如果我只是打印出list(current_user.stocks) ,它会返回给我:

[<Stocks GOOGL>, <Stocks TSLA>]

Stocks is a table/class i'm using in flask-sqlalchemy. Stocks 是我在 flask-sqlalchemy 中使用的表/类。 I want the JSON to look something like this:我希望 JSON 看起来像这样:

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

I have no problem with <Stocks GOOGL> and the other array element being a string.我对<Stocks GOOGL>没有问题,而另一个数组元素是字符串。

Any ideia as to how to jsonify this inside a dict?关于如何在 dict 中将其 jsonify 的任何想法? Thanks in advance!提前致谢!

The example you gave is not a valid JSON.您提供的示例不是有效的 JSON。 You can try something like:您可以尝试以下方法:

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

Then jsonify(r) should produce something like:然后jsonify(r)应该产生类似的东西:

{"stocks": ["<Stocks GOOGL>", "<Stocks TSLA>"]} # Note that these are strings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM