3

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"])
1
  • Could you give more details / context please ? Commented Dec 28, 2020 at 9:28

2 Answers 2

1

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"])
Sign up to request clarification or add additional context in comments.

7 Comments

response = requests.get('api.thecatapi.com/v1/images/search') x = response.json() json_obj = json.loads(x) for i in json_obj: print(i["url"]) I get: TypeError: the JSON object must be str, bytes or bytearray, not list
You don't need to do json.load after you already received the json object. I did it to convert the string into json. You can see the edited answer for requests. @EloBenc
Thank you! That second bit of code worked!
If the issue is resolved, please mark the answer as accepted. @EloBenc
I will do it as soon as i can :D 4 minutes to go.
|
0
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

Comments

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.