M
M
Mishcake2021-08-06 19:33:11
Python
Mishcake, 2021-08-06 19:33:11

How to return the right number of elements in requests.get?

Hello. I'm using the API to one news resource that does not have the ability to set the number of returned articles through a parameter. The data is returned in json format.

Is it possible to somehow limit the amount of returned data in this case?

response = requests.get(url)
print(response.text) # возвращается строка с кучей данных. А хочу получить только один элемент в json-древе

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WolfInChains, 2021-08-07
@Mishcake

Well, if the api does not provide for a choice of the number of articles, then it can be reduced through slices.
This example truncates the list of articles to the first 5 pieces.

response = requests.get(url)
response_json = response.json()
elements = response_json["result"][:5]

You can put it in a function and cut it off.
Here is an example, where response_json is your json response from the request, amount is how many articles to leave.
def cutter(response_json, amount):
    return response_json["result"][:amount]

Or whatever is more convenient for you.

K
kirillinyakin, 2021-08-06
@kirillinyakin

response_json = response.json()
first_element = response_json[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question