【问题标题】:How to take 'url' variable from this JSON in Python如何在 Python 中从此 JSON 中获取“url”变量
【发布时间】:2021-04-05 02:14:36
【问题描述】:

如何从这个 JSON 字符串中打印出“url”的内容。

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

我只想在我的 python 控制台中打印它。如果重要的话,该 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"])

【问题讨论】:

  • 您能否提供更多详细信息/上下文?

标签: python json string api url


【解决方案1】:

假设您的 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"])

如果你想直接从 URL 接收 JSON,你可以直接这样做:

import requests
for i in requests.get("https://api.thecatapi.com/v1/images/search").json():
    print(i["url"])

【讨论】:

  • 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"]) 我得到: TypeError: JSON 对象必须是 str、bytes 或 bytearray,而不是 list
  • 收到json对象后就不需要再做json.load了。我这样做是为了将字符串转换为 json。您可以查看请求的已编辑答案。 @EloBenc
  • 谢谢!第二段代码起作用了!
  • 如果问题得到解决,请将答案标记为已接受。 @EloBenc
  • 我会尽快完成 :D 4 分钟。
【解决方案2】:
data = {"breeds":[],"id":"bkv","url":"https://cdn2.thecatapi.com/images/bkv.jpg","width":800,"height":600}
print(data["url"])

print(data.values()[2])

这两种方法中的一种有效吗?如果没有,我可以查看您针对此问题的完整代码(如果这不是全部)

希望有效果

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 2011-02-13
    • 2014-03-14
    • 2016-04-25
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多