0
import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}

url = f'https:............'
response = requests.get(url, headers=headers).json()
events = response['events']
for event in events:
    List_of_Urls = []
    List_of_Urls.append(event['id'])

    slug = event['slug']

    for List_of_Url in List_of_Urls:
        try:
            url2 = f'https://.............../{List_of_Url}/.........'
            response2 = requests.get(url2, headers=headers).json()
            
            if response2['graphPoints']:
                print(slug)
        except:
            pass

Response JSON example 1:

{
  "graphPoints": [
    {
      "minute": 1,
      "value": -2
    }

Response JSON example 2:

{
  "error": {
    "code": 404,
    "message": "Not Found"
  }
}

My idea is that if there is graphPoints in JSON, then printing the slug value, but in the direct if response2['graphPoints']: value for true or false doesn't work, how should I make it work?

2
  • Why don't you just check for response code and ignore non 200? Commented Dec 6, 2021 at 20:29
  • besides the @chasmani's answer, there is also an option to exploit short-circuitry and just print(response2.get('graphPoints') and slug) Commented Dec 6, 2021 at 20:52

1 Answer 1

1

If its a JSON object I think you can just do:

if 'graphPoints' in response2:
    print(slug)
Sign up to request clarification or add additional context in comments.

6 Comments

Hello friend @chasmani , thanks for the support. I added two links inside a question to demonstrate the answers JSON gives. I tried the two ways you indicated but I was not successful!
the second one is an antipattern. key in some_dict is the intended way of checking dict membership
@BrondbyIF please post more information on how it doesn't work. The first snippet is actually the one you're looking for
Hi @Marat Actually I don't know why it's not working, the code runs and doesn't print any value, but when I use if (response2['graphPoints'][0]['minute'] >= 1):, then it returns the prints, so I work around the problem but I wanted something exact on top of the graphPoints existence
@BrondbyIF the answer contains a typo, graphpoints instead of graphPoints
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.