【发布时间】:2019-06-02 21:31:19
【问题描述】:
我正在使用异步方法返回一个对象数组,我收到“TypeError: is not JSON serializable”错误,我不知道如何纠正它。这是我的代码:
async def fetch(session, url):
async with session.get(url) as response:
return await response.text
class NewStoriesHandler(tornado.web.RequestHandler):
async def get(self):
self.set_header("Access-Control-Allow-Origin", "*")
response = requests.get(
"https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty")
data = response.json()
story_list = []
async with aiohttp.ClientSession() as session:
for url in data:
story_list.append(fetch(session, url))
print(story_list)
self.write(json.dumps(story_list, default=json_util.default))
self.finish()
我试图将 Json 返回到该方法,但没有成功,我不确定它期望返回什么。循环为每次调用返回一个对象并将其附加到数组中。
【问题讨论】:
-
请提供
print(story_list)行的输出 -
意思是它所说的——如果一个对象包含 Python 不知道如何转换为 JSON 的东西,你会得到那个错误。除非您告诉我们
fetch(session, url)返回的内容,否则我们不知道如何解决。 -
它返回一个对象数组
-
什么特定类型的对象?有些对象是可序列化的,有些则不是。
-
您正在运行
print(story_list),但您没有向我们展示print()输出的内容。这是非常相关的信息。
标签: python json python-asyncio aiohttp