【问题标题】:How to Extract Particular Data From JSON Python如何从 JSON Python 中提取特定数据
【发布时间】:2021-10-05 17:47:33
【问题描述】:

我有这个 json:

如何解析所有的名字,里面的书,我可以得到一个:

import requests
url = "https://www.storytel.com/api/search.action?q=white%20feather"
r = requests.get(url)
cont = r.json()
# print(cont)
print(cont['books'][0]['book']['name'])

但是我怎样才能得到所有的“名字”呢? 我试过这个但没有用:

data = cont['books']

for book in data:
    print(cont['book']['name'])

错误是:

Traceback (most recent call last): File "testing.py", line 12, in module> print(cont['book']['name']) KeyError: 'book' 

【问题讨论】:

  • 你能提供更多关于这个“不起作用”的细节吗?
  • 你也可以发布回溯!?
  • 回溯(最近一次调用):文件“testing.py”,第 12 行,在 print(cont['book']['name']) KeyError: 'book'

标签: python json


【解决方案1】:

您没有在循环中使用 变量(相对于 字符串book

【讨论】:

  • 对不起是什么意思?
  • 你写了for book...,但从未真正使用过book
  • 你是对的。谢谢你作为第一个答案,我会给你答案。
  • tbh 这也是解释问题原因的唯一答案。我认为这本身就值得一票。
【解决方案2】:

您在循环中引用了不正确的变量,而不是 cont 您应该引用 book 实例。

import requests
import json

url = "https://www.storytel.com/api/search.action?q=white%20feather"
r = requests.get(url)
cont = r.json()
data = cont['books']
for book in data:
    print(book['book']['name']) # here instead of pointing to Book instance, you are pointing to cont dictionary which is creating the issue

输出:

The White Feather
The White Feather
Little White Feather
The White Feather Murders
The White Feather Killer
The White Feather Hex

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2021-07-01
  • 2020-10-02
  • 2015-02-18
  • 2015-04-15
相关资源
最近更新 更多