-1

Needed simple help for a beginner :) Below the python code:

url = "theurl"
headers = {'Accept': 'application/json', 'X-auth-Token': 'thetoken'}
response = requests.get(url, headers=headers)
json_data = response.json()
nexturl = json_data['next']

Below the response from the request:

{
"data": [
    {
        "id": 112,
        "name": "sample",
        "type": "sample",
        "sku": "SKUF46386",
        "description": "",
        "weight": 0,
        "width": 0,
        "depth": 0,
        "height": 0,
        "price": 162,
        "cost_price": 0,
        "retail_price": 0,
        "sale_price": 0,
        "map_price": 0,
        "tax_class_id": 0,
        "product_tax_code": "",
        "calculated_price": 162,
        "categories": [
            25
        ]
],
"meta": {
    "pagination": {
        "total": 14526,
        "count": 50,
        "per_page": 50,
        "current_page": 1,
        "total_pages": 291,
        "links": {
            "next": "?page=2&limit=50",
            "current": "?page=1&limit=50"
        },
        "too_many": false
    }
}

}

How to grab this value: meta.pagination.links.next and store it within a new variable. When I try to run the code the Idle comes with a message: KeyError: 'next'

Peter K
  • 13
  • 1

1 Answers1

1

The response is a dictionary. To get a value for a specified key from a dictionary, you need to: your_dict['key'].

In your case, there is a response dictionary with two keys: "data" and "meta". So to get value (also a dictionary) for the "meta" key, you have to: `response["meta"].

The value you're looking for (for key "next") is stored deeper - in the dictionary you've just got with the "meta" key, there is a "pagination" key, whose value is another dictionary with a key "links", whose value is again another dictionary with the wanted key "next".
So, to get the value for the "next" key you have to:

response["meta"]["pagination"]["links"]["next"]`
maciejwww
  • 1,067
  • 1
  • 13
  • 26