-1

I'm trying to access an API with python and I'm getting json values.

But I can't get the values ​​of "Variants" can someone help me with this? Thanks.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import json

URL = "https://www.sonos.com/de-at/getproductpricejson?pid=sub-mini,ray,roam,roam- 
sl,arc,five,sub,move,one,one-sl,beam,port,amp,boost,ceiling-speaker-pair,wall-speaker- 
pair,outdoor-speaker-pair,two-room-set-roam,roam-and-wireless-charger-set,roam-sl-and- 
wireless-charger-set,portable-set-move-roam,2-room-music-system-one,indoor-outdoor-set,two- 
room-set-one-sl,two-room-pro-five,mounted-ray-set,beam-mount-set,arc-mount-set,two-room-set- 
ray-roam,surround-set-ray-one-sl-pair,surround-set-beam-one-sl-pair,surround-set-arc-one-sl- 
pair,entertainment-set-ray-sub-mini,entertainment-set-beam-sub-mini,3-1-entertainment-set- 
beam-sub,entertainment-set-arc-sub,multiroom-entertainment-set-arc-and-move,immersive-set-ray- 
sub-mini-one-sl,immersive-set-beam-sub-mini-one-sl,5-1-surround-set-beam-sub-one-sl,surround- 
set-arc-sub-one-sl,amp-and-ceiling-set,amp-and-wall-set,amp-and-outdoor-set,vinyl-set-five- 
pro-ject-t1-turntable,wall-mount-one-play1,wall-mount-one-play1-pair,shelf-one-play1,speaker- 
stand-pair-one-play1,wall-hook"

r = requests.get(URL)
page = r.json()

print(page)

for element in page:
#print(element)
print(element["variants"])

I get a few results but then the error comes

    print(element["variants"])
KeyError: 'variants'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Then the `elements` object doesn't have a `'variants'` key... What did your debugging show? Such as `print(element)` or `print(element.keys)`? Or, better still, use the debugging mode in your IDE and explore the object manually? *(Remember; keys are case sensitive.)* – MatBailie Jan 30 '23 at 17:57
  • What do you need help with exactly? It looks like the key you want doesn't exist, so is there maybe documentation for the API that could tell you why this is? Or is this a bug in the API? Anyway, please read [How to ask a good question](/help/how-to-ask). See also [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/q/284236/4518341) – wjandrea Jan 30 '23 at 17:59

2 Answers2

2

Please try this:

for element in page:
    if "variants" in element.keys():
        print(element["variants"])

The reason why you're getting an error after a point is that there's no variants on id:10

JSON shown as a nested list, elements 9 and 10

Deep Bhatt
  • 313
  • 1
  • 11
1

Hey you can just modify your code to check if a key exsits in your element like it was sayed in this issue: Check if a given key already exists in a dictionary.
When modifying your code looks like this :

for element in page:
#print(element)
    if 'variants' in element:
            print(element['variants'])`