Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python print only .jpg url's from json

How can I print only .jpg/.png urls from API using json?

`

import requests
import json

r = requests.get("https://random.dog/woof.json")
print("Kod:", r.status_code)

def jprint(obj):
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)

jprint(r.json())

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Results:

`

{
    "fileSizeBytes": 78208,
    "url": "https://random.dog/24141-29115-27188.jpg"
}

`

I tried .endswith() but without any success.
I’m beginner.

>Solution :

This example will use str.endswith to check, if dictionary value under the key url contains the string .jpg or .png.

I’m doing 10 requests and using time.sleep to wait 1 second between each request:

import requests
from time import sleep

url = "https://random.dog/woof.json"

for i in range(10):
    print("Attempt {}".format(i + 1))

    data = requests.get(url).json()
    if data["url"].endswith((".jpg", ".png")):
        print(data["url"])

    sleep(1)

Prints (for example, data returned from the server is random):

Attempt 1
https://random.dog/aa8e5e24-5c58-4963-9809-10f4aa695cfc.jpg
Attempt 2
https://random.dog/5b2a4e74-58da-4519-a67b-d0eed900b676.jpg
Attempt 3
https://random.dog/56217498-0e6b-4c24-bdd1-cc5dbb2201bb.jpg
Attempt 4
https://random.dog/l6CIQaS.jpg
Attempt 5
Attempt 6
Attempt 7
https://random.dog/3b5eae93-b3bd-4012-b789-64eb6cdaac65.png
Attempt 8
https://random.dog/oq9izk0057hy.jpg
Attempt 9
Attempt 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading