简体   繁体   English

如何从 Python 中的 JSON 中获取“url”变量

[英]How to take 'url' variable from this JSON in Python

How can I print out content of "url" from this JSON string.如何从此 JSON 字符串中打印出“url”的内容。

[{"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.我只想在我的 python 控制台中打印它。 That JSON is from https://api.thecatapi.com/v1/images/search if it matters.如果重要的话,JSON 来自https://api.thecatapi.com/v1/images/search

    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"])

Assuming there are multiple JSON elements inside your JSON string:假设 JSON 字符串中有多个 JSON 元素:

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:如果您想直接从 URL 接收 JSON,您可以直接这样做:

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希望它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM