Python 3.x 如何在python3请求模块中仅获取json文件的一部分

Python 3.x 如何在python3请求模块中仅获取json文件的一部分,python-3.x,python-requests,google-classroom,Python 3.x,Python Requests,Google Classroom,所以,我正在用Python编写一个程序,使用请求模块从google教室API获取数据。我从教室里得到了完整的json响应,如下所示: {'announcements': [{'courseId': '#############', 'id': '###########', 'text': 'This is a test','state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##########/p/####

所以,我正在用Python编写一个程序,使用请求模块从google教室API获取数据。我从教室里得到了完整的json响应,如下所示:

{'announcements': [{'courseId': '#############', 'id': '###########', 'text': 'This is a test','state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##########/p/###########', 'creationTime': '2021-04-11T10:25:54.135Z', 'updateTime': '2021-04-11T10:25:53.029Z', 'creatorUserId': '###############'}, {'courseId': '############', 'id': '#############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/#############/p/##################', 'creationTime': '2021-04-11T10:24:30.952Z', 'updateTime': '2021-04-11T10:24:48.880Z', 'creatorUserId': '##############'}, {'courseId': '##################', 'id': '############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##############/p/################', 'creationTime': '2021-04-11T10:23:42.977Z', 'updateTime': '2021-04-11T10:23:42.920Z', 'creatorUserId': '##############'}]}
实际上,我无法将其转换为一个漂亮的格式,所以只需在从http请求中获得它时粘贴它即可。我实际上希望做的是从服务中请求前几个公告(比如1、2、3,根据需要而定),而我得到的是自教室创建以来所做的所有公告(如示例3公告)。现在,我相信获取所有公告可能会使程序变慢,因此我更希望只获取所需的公告。有没有办法通过传递一些参数或其他什么来做到这一点?google教室提供了一些直接的功能,但是我在不久之后遇到了这些功能,并且已经使用requests模块编写了所有内容,这需要更改很多我希望避免的事情。但是,如果不可避免,我也会走这条路。

回答: 使用
pageSize
字段,使用
updateTime asc
orderBy
参数,限制
announcements:list
请求中所需的响应数量

更多信息: 根据:

orderBy
string

可选的结果排序。以逗号分隔的字段列表,带有可选的排序方向关键字。支持的字段是
updateTime
。支持的方向关键字是
asc
desc
。如果未指定,
updateTime desc
是默认行为。示例:
updateTime asc
updateTime

以及:

pageSize
integer

要返回的最大项目数。零或未指定表示服务器可以分配最大值

因此,假设您想要课程的前3条公告,您可以使用
pageSize
3
,以及
updateTime asc的
orderBy

#版权所有2021谷歌有限责任公司。
#SPDX许可证标识符:Apache-2.0
服务=构建(“教室”、“v1”、凭证=凭证)
asc=“updateTime asc”
页面大小=3
#调用教室API
结果=service.courses().announcements().list(pageSize=3,orderBy=asc).execute()
或HTTP请求示例:

GET https://classroom.googleapis.com/v1/courses/[COURSE_ID]/announcements
      ?orderBy=updateTime%20asc
      &pageSize=2
      &key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
我希望这对你有帮助

参考资料:

这给了我想法,但没有给我直接的解决方案,但谢谢。我想要的是使用requests库发送GET请求,而不是使用Google提供的build等函数。你说pageSize和orderBy作为字段让我有了把它们作为参数的想法,并且成功了。所以再次感谢!!干杯