How to take 'url' variable from this JSON in Python

Viewed 97

How can I print out content of "url" from this JSON string.

[{"breeds":[],"id":"bkv","url":"https://cdn2.thecatapi.com/images/bkv.jpg","width":800,"height":600}]

I want to just print that in my python console. That JSON is from https://api.thecatapi.com/v1/images/search if it matters.

    response = requests.get('https://api.thecatapi.com/v1/images/search')
x = response.json()
json_obj = json.loads(x)
for i in json_obj:
    print(i["url"])
2 Answers

Assuming there are multiple JSON elements inside your JSON string:

import json
json_string = '[{"breeds":[],"id":"bkv","url":"https://cdn2.thecatapi.com/images/bkv.jpg","width":800,"height":600}]'
json_obj = json.loads(json_string)
for i in json_obj:
    print(i["url"])

If you want to directly receive the JSON from the URL, you can do this directly:

import requests
for i in requests.get("https://api.thecatapi.com/v1/images/search").json():
    print(i["url"])
data = {"breeds":[],"id":"bkv","url":"https://cdn2.thecatapi.com/images/bkv.jpg","width":800,"height":600}
print(data["url"])

or

print(data.values()[2])

Does one of these two work? If not, may i see the full code that you have for this problem (if this isn't everything)

Hope it works

Related