How to Slice JSON data

I am developing an application which will involve scrapping news, the api am using scrapes more than 40 news per call. Please how can I limit the output to, say, 10

The following code may explain my goal better

in the views.py

def news_getter(request):
    **api_content = json.loads(api_request.content)[:10]**
    template='news.html'
    context={'news':api_content}
    return render(request, template, context)

in the news.html

{% for n in news.Data%}
   {{n.body}}
{% endfor %}

Unfortunately that didn’t work as I keep getting TypeError: unhashable type: ‘slice’
I will also appreciate proper documentation that can make me understand JSON file very well, thanks in anticipation.

It looks like the shape of api_request.content is:

{
    "Data": [
        {...},
        ...
    ]
}

You need to slice the api_content["Data"] element.

def news_getter(request):
    api_content = json.loads(api_request.content)
    template='news.html'
    context={'news': api_content["Data"][:10]}
    return render(request, template, context)

Then in your template you no longer need to use news.Data since news is set to the Data element in the view.

{% for n in news%}
   {{n.body}}
{% endfor %}
1 Like