【问题标题】:how can I get a specific element in json with python如何使用 python 获取 json 中的特定元素
【发布时间】:2020-04-02 13:01:42
【问题描述】:

我想用 python 访问一个特定的元素,但是我不能

import json
import requests

search_book = str(input("search a book: "))
request = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + search_book)
request_text = request.text

data = request_text
print(data['items']['volumeInfo']['title'])

错误是:

Traceback(最近一次调用最后一次):文件 “C:/Users/ddvit/Documents/programming/python/books/books.py”,第 9 行, 在 print(data['items']['volumeInfo']['title']) TypeError: 字符串索引必须是整数

提前非常感谢你:)

【问题讨论】:

  • 这是 ot python 这是文本

标签: python json api google-books


【解决方案1】:

要获取 JSON 格式的结果,您需要加载它 json.loads(request.text) 或直接使用 request.json() 检索

那么items是一个数组,所以不能直接访问信息,

  • 你可以迭代它,然后得到标题

    data = request.json()
    for item in data['items']:
        title = item['volumeInfo']['title']
        print(title)
    
  • 直接访问一个

    print(data['items'][0]['volumeInfo']['title'])
    

【讨论】:

    【解决方案2】:

    您从响应中获取原始文本,请改用json() 方法:

    import json
    import requests
    
    search_book = str(input("search a book: "))
    response = requests.get("https://www.googleapis.com/books/v1/volumes?q=" + search_book)
    data = response.json()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多